You are here

function google_api_client_update_8001 in Google API PHP Client 8.4

Same name and namespace in other branches
  1. 8.2 google_api_client.install \google_api_client_update_8001()
  2. 8.3 google_api_client.install \google_api_client_update_8001()

Create Entity Type for Google Api Client.

File

./google_api_client.install, line 32
Install and uninstall functions for the Google api client module.

Code

function google_api_client_update_8001() {
  \Drupal::entityTypeManager()
    ->clearCachedDefinitions();
  $entity_type = \Drupal::entityTypeManager()
    ->getDefinition('google_api_client');
  \Drupal::entityDefinitionUpdateManager()
    ->installEntityType($entity_type);

  // Entity table is ready let's copy previous record as first account.
  $settings = \Drupal\Component\Serialization\Json::decode(\Drupal::config('google_api_client.settings')
    ->get('credentials'));
  $scopes = \Drupal::config('google_api_client.settings')
    ->get('scopes');
  $scopes = array_map('trim', explode(PHP_EOL, $scopes));

  //Let's find services for these scopes.
  $all_services = _google_api_client_google_services_names();
  $all_services = array_keys($all_services);
  $all_scopes = google_api_client_google_services_scopes($all_services);
  $services = [];
  foreach ($scopes as $scope) {
    foreach ($all_scopes as $service_name => $service_scopes) {
      if (in_array($scope, $service_scopes)) {
        $services[] = $service_name;
        break;
      }
    }
  }
  $services = array_unique($services);
  $token = unserialize(\Drupal::config('google_api_client.tokens')
    ->get('google_access_token'));
  $token = \Drupal\Component\Serialization\Json::encode($token);
  $account = [
    'name' => 'Google Api Client',
    'client_id' => $settings['web']['client_id'],
    'client_secret' => $settings['web']['client_secret'],
    'access_token' => $token,
    'services' => $services,
    'access_type' => 1,
  ];
  $google_api_client = \Drupal::entityTypeManager()
    ->getStorage('google_api_client')
    ->create($account);
  if ($token) {
    $google_api_client
      ->setAuthenticated(TRUE);
  }
  $google_api_client
    ->setScopes($scopes);
  $google_api_client
    ->save();

  // New account created, now delete old config.
  \Drupal::configFactory()
    ->getEditable('google_api_client.settings')
    ->delete();
  \Drupal::configFactory()
    ->getEditable('google_api_client.tokens')
    ->delete();
}