You are here

public function FeedsYouTubeFetcher::getClientFactory in Feeds: YouTube Parser 8

Helper function to get client factory.

Parameters

string $id: The feed Id.

Return value

Google_Client|null

1 call to FeedsYouTubeFetcher::getClientFactory()
FeedsYouTubeFetcher::get in src/Feeds/Fetcher/FeedsYouTubeFetcher.php
Make the API queries to get the data the parser needs.

File

src/Feeds/Fetcher/FeedsYouTubeFetcher.php, line 51

Class

FeedsYouTubeFetcher
Constructs FeedsYouTubeFetcher object.

Namespace

Drupal\feeds_youtube\Feeds\Fetcher

Code

public function getClientFactory($id) {
  $config = $this
    ->getConfiguration();
  $cid = $this
    ->getAccessTokenCacheId($id);
  $google_access_token = \Drupal::service('cache.feeds_youtube_tokens')
    ->get($cid);
  if (!empty($config['google_oauth_client_id']) && !empty($config['google_oauth_client_secret']) && !empty($config['google_developer_key'])) {
    $client = new \Google_Client();
    $client
      ->setClientId($config['google_oauth_client_id']);
    $client
      ->setClientSecret($config['google_oauth_client_secret']);
    $client
      ->setApprovalPrompt('force');
    $client
      ->setAccessType('offline');
    $client
      ->setDeveloperKey($config['google_developer_key']);
    $client
      ->setScopes('https://www.googleapis.com/auth/youtube.readonly');
    $current_path = \Drupal::service('path.current')
      ->getPath();
    $path_alias = \Drupal::service('path_alias.manager')
      ->getAliasByPath($current_path);
    $current_url = Url::fromUserInput($path_alias, [
      'absolute' => TRUE,
    ])
      ->toString();
    $redirect = filter_var($current_url, FILTER_SANITIZE_URL);
    $client
      ->setRedirectUri($redirect);
    if (!empty($google_access_token->data)) {
      $client
        ->setAccessToken($google_access_token->data);
      if ($client
        ->isAccessTokenExpired()) {
        $client
          ->refreshToken($client
          ->getRefreshToken());

        // Save refreshed access token.
        $cache_tags = [
          'feeds_youtube:google_access_token',
        ];
        \Drupal::service('cache.feeds_youtube_tokens')
          ->set($cid, $client
          ->getAccessToken(), CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
      }
    }
    return $client;
  }
  else {
    \Drupal::messenger()
      ->addWarning($this
      ->t('Google API access is not configured.'));
  }
}