You are here

public function OverrideAppKeysOnGenerate::overrideAppKeyOnGenerate in Apigee Edge 8

Overrides auto-generated key for an app.

Parameters

\Drupal\apigee_edge\Event\AppCredentialGenerateEvent $event: App credential generation event.

Throws

\Drupal\Core\TempStore\TempStoreException

File

tests/modules/apigee_edge_test_app_keys/src/EventSubscriber/OverrideAppKeysOnGenerate.php, line 69

Class

OverrideAppKeysOnGenerate
Developer app credential generate event subscriber.

Namespace

Drupal\apigee_edge_test_app_keys\EventSubscriber

Code

public function overrideAppKeyOnGenerate(AppCredentialGenerateEvent $event) {
  $random = new Random();
  if ($event
    ->getAppType() === AppCredentialGenerateEvent::APP_TYPE_DEVELOPER) {
    $credential_controller = $this->devAppCredentialControllerFactory
      ->developerAppCredentialController($event
      ->getOwnerId(), $event
      ->getAppName());
  }
  else {

    // TODO Finish when Company apps gets supported.
  }
  $prefix = apigee_edge_test_app_keys_get_prefix();
  try {
    $credential_controller
      ->delete($event
      ->getCredential()
      ->getConsumerKey());
    $new_consumer_key = "{$prefix}-{$random->name()}";
    try {
      $credential_controller
        ->create($new_consumer_key, "{$prefix}-{$random->name()}");
      try {
        $products = array_map(function (CredentialProduct $item) {
          return $item
            ->getApiproduct();
        }, $event
          ->getCredential()
          ->getApiProducts());
        $credential_controller
          ->addProducts($new_consumer_key, $products);
      } catch (ApiException $e) {
        watchdog_exception('apigee_edge', $e, 'Unable to assign API products to the newly generated API key on Apigee Edge for @app app. !message', [
          '@app' => "{$event->getOwnerId()}:{$event->getAppName()}",
        ]);
        try {
          $credential_controller
            ->delete($new_consumer_key);
        } catch (ApiException $e) {
          watchdog_exception('apigee_edge', $e, 'Unable to delete newly generated API key after API product re-association has failed on Apigee Edge for @app app. !message', [
            '@app' => "{$event->getOwnerId()}:{$event->getAppName()}",
          ]);
        }
      }
    } catch (ApiException $e) {
      watchdog_exception('apigee_edge', $e, 'Unable to create new API key on Apigee Edge for @app app. !message', [
        '@app' => "{$event->getOwnerId()}:{$event->getAppName()}",
      ]);
    }
  } catch (ApiException $e) {
    watchdog_exception('apigee_edge', $e, 'Unable to delete auto-generated key of @app app on Apigee Edge. !message', [
      '@app' => "{$event->getOwnerId()}:{$event->getAppName()}",
    ]);
  }
}