You are here

public function Server::postSave in OAuth2 Server 8

Same name and namespace in other branches
  1. 2.0.x src/Entity/Server.php \Drupal\oauth2_server\Entity\Server::postSave()

Acts on a saved entity before the insert or update hook is invoked.

Used after the entity is saved, but before invoking the insert or update hook. Note that in case of translatable content entities this callback is only fired on their current translation. It is up to the developer to iterate over all translations if needed.

Parameters

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

bool $update: TRUE if the entity has been updated, or FALSE if it has been inserted.

Overrides EntityBase::postSave

File

src/Entity/Server.php, line 118

Class

Server
Defines the OAuth2 server entity.

Namespace

Drupal\oauth2_server\Entity

Code

public function postSave(EntityStorageInterface $storage, $update = TRUE) {
  parent::postSave($storage, $update);
  $old_settings = isset($this->original) ? $this->original->settings : [];
  $previous_value = !empty($old_settings['use_openid_connect']);
  $current_value = !empty($this->settings['use_openid_connect']);
  if (!$previous_value && $current_value) {
    $openid_scopes = [
      'openid' => new FormattableMarkup('Know who you are on @site', [
        '@site' => \Drupal::config('system.site')
          ->get('name'),
      ]),
      'offline_access' => "Access the API when you're not present.",
      'email' => 'View your email address.',
      'profile' => 'View basic information about your account.',
    ];
    foreach ($openid_scopes as $id => $description) {

      /** @var \Drupal\oauth2_server\ScopeInterface $scope */
      $scope = $this
        ->entityTypeManager()
        ->getStorage('oauth2_server_scope')
        ->load($this
        ->id() . '_' . $id);
      if (!$scope) {
        $scope = Scope::create([
          'scope_id' => $id,
          'server_id' => $this
            ->id(),
          'description' => $description,
        ]);
        $scope
          ->save();
      }
    }
  }

  // If OpenID Connect was just disabled, delete its scopes.
  if ($previous_value && !$current_value) {
    $scope_names = [
      'openid',
      'offline_access',
      'email',
      'profile',
    ];

    /** @var \Drupal\oauth2_server\ScopeInterface[] $scopes */
    $scopes = $this
      ->entityTypeManager()
      ->getStorage('oauth2_server_scope')
      ->loadByProperties([
      'server_id' => $this
        ->id(),
      'scope_id' => $scope_names,
    ]);
    foreach ($scopes as $scope) {
      $scope
        ->delete();
    }

    // If we just deleted a default scope, update the server.
    if (in_array($this->settings['default_scope'], $scope_names)) {
      $this->settings['default_scope'] = '';
      $this
        ->save();
    }
  }
}