You are here

private function GoogleApiClientService::setAccessToken in Google API PHP Client 8.2

Same name and namespace in other branches
  1. 8.4 src/Service/GoogleApiClientService.php \Drupal\google_api_client\Service\GoogleApiClientService::setAccessToken()
  2. 8.3 src/Service/GoogleApiClientService.php \Drupal\google_api_client\Service\GoogleApiClientService::setAccessToken()

Wrapper for Google_Client::setAccessToken.

Return value

bool Was the token added or not?

Throws

\Drupal\Core\Entity\EntityStorageException

1 call to GoogleApiClientService::setAccessToken()
GoogleApiClientService::getClient in src/Service/GoogleApiClientService.php
Function to retrieve the google client for different operations.

File

src/Service/GoogleApiClientService.php, line 160

Class

GoogleApiClientService
Class Google API Client Service.

Namespace

Drupal\google_api_client\Service

Code

private function setAccessToken() {

  // If there was something in cache.
  if ($access_token = $this->googleApiClient
    ->getAccessToken()) {

    // Check if the current token is expired?
    if ($this->googleClient
      ->isAccessTokenExpired()) {

      // Refresh the access token using refresh token if it is set.
      if ($this->googleClient
        ->getRefreshToken() != '') {
        $tokenUpdated = $this->googleClient
          ->fetchAccessTokenWithRefreshToken($this->googleClient
          ->getRefreshToken());

        // Now that there is a new access token in cache,
        // set it into the client.
        if ($tokenUpdated != FALSE) {
          $this->googleClient
            ->setAccessToken($tokenUpdated);
          $this->googleApiClient
            ->setAccessToken($tokenUpdated);
          $this->googleApiClient
            ->save();

          // There should be a new unexpired token.
          return TRUE;
        }
      }

      // Else the token fetch from refresh token failed.
      $this->googleClient
        ->revokeToken();
      $this->googleApiClient
        ->setAuthenticated(FALSE);
      $this->googleApiClient
        ->setAccessToken('');
      $this->googleApiClient
        ->save();

      // Unable to update token.
      return FALSE;
    }
    $this->googleClient
      ->setAccessToken($access_token);

    // Token is set and is valid.
    return TRUE;
  }

  // There is no token in db.
  return FALSE;
}