You are here

abstract class AppApiKeyAddFormBase in Apigee Edge 8

Provides app API key add base form.

Hierarchy

Expanded class hierarchy of AppApiKeyAddFormBase

1 file declares its use of AppApiKeyAddFormBase
TeamAppApiKeyAddForm.php in modules/apigee_edge_teams/src/Form/TeamAppApiKeyAddForm.php

File

src/Form/AppApiKeyAddFormBase.php, line 34

Namespace

Drupal\apigee_edge\Form
View source
abstract class AppApiKeyAddFormBase extends FormBase {

  /**
   * The app entity.
   *
   * @var \Drupal\apigee_edge\Entity\AppInterface
   */
  protected $app;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'apigee_edge_app_api_key_add_form';
  }

  /**
   * Returns the app credential controller.
   *
   * @param string $owner
   *   The developer id (UUID), email address or team (company) name.
   * @param string $app_name
   *   The name of an app.
   *
   * @return \Drupal\apigee_edge\Entity\Controller\AppCredentialControllerInterface
   *   The app api-key controller.
   */
  protected abstract function appCredentialController(string $owner, string $app_name) : AppCredentialControllerInterface;

  /**
   * Returns the redirect url for the app.
   *
   * @return \Drupal\Core\Url
   *   The redirect url.
   */
  protected abstract function getRedirectUrl() : Url;

  /**
   * Returns the list of API product that the user can see on the form.
   *
   * @return \Drupal\apigee_edge\Entity\ApiProductInterface[]
   *   Array of API product entities.
   */
  protected abstract function apiProductList(array $form, FormStateInterface $form_state) : array;

  /**
   * Returns the app owner id. This needs to come from the route.
   *
   * @return string
   *   The app owner id.
   */
  protected abstract function getAppOwner() : string;

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?AppInterface $app = NULL) {
    $this->app = $app;
    $form['owner'] = [
      '#type' => 'value',
      '#value' => $this
        ->getAppOwner(),
    ];
    $form['message'] = [
      '#type' => 'html_tag',
      '#tag' => 'h3',
      '#value' => $this
        ->t('Do you really want to create a new API key for this @entity_type?', [
        '@entity_type' => mb_strtolower($app
          ->getEntityType()
          ->getSingularLabel()),
      ]),
    ];
    $form['expiry'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Set an expiry date'),
      '#required' => TRUE,
      '#options' => [
        'never' => $this
          ->t('Never'),
        'date' => $this
          ->t('Date'),
      ],
      '#default_value' => 'never',
    ];
    $form['expiry_date'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Select date'),
      '#states' => [
        'visible' => [
          ':input[name="expiry"]' => [
            'value' => 'date',
          ],
        ],
      ],
    ];
    $form['actions'] = [
      '#type' => 'actions',
      'cancel' => [
        '#type' => 'link',
        '#title' => $this
          ->t('Cancel'),
        '#attributes' => [
          'class' => [
            'button',
          ],
        ],
        '#url' => $this
          ->getRedirectUrl(),
      ],
      'submit' => [
        '#type' => 'submit',
        '#value' => $this
          ->t('Confirm'),
        '#button_type' => 'primary',
      ],
    ];
    $form['#attached']['library'][] = 'apigee_edge/apigee_edge.components';
    $form['#attributes']['class'][] = 'apigee-edge--form';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $expiry = $form_state
      ->getValue('expiry');
    $expiry_date = $form_state
      ->getValue('expiry_date');

    // Validate expiration date.
    if ($expiry === 'date') {
      if ((new \DateTimeImmutable($expiry_date))
        ->diff(new \DateTimeImmutable())->invert !== 1) {
        $form_state
          ->setError($form['expiry_date'], $this
          ->t('The expiration date must be a future date.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $expiry = $form_state
      ->getValue('expiry');
    $expiry_date = $form_state
      ->getValue('expiry_date');
    $expires_in = $expiry === 'date' ? (strtotime($expiry_date) - time()) * 1000 : -1;
    $selected_products = [];
    $api_products = $this
      ->getApiProductsForApp($this->app);
    if (count($api_products)) {
      $selected_products = array_map(function (CredentialProductInterface $api_product) {
        return $api_product
          ->getApiproduct();
      }, $api_products);
    }
    $args = [
      '@app' => $this->app
        ->label(),
    ];
    try {
      $this
        ->appCredentialController($this->app
        ->getAppOwner(), $this->app
        ->getName())
        ->generate($selected_products, $this->app
        ->getAttributes(), $this->app
        ->getCallbackUrl() ?? "", [], $expires_in);
      Cache::invalidateTags($this->app
        ->getCacheTags());
      $this
        ->messenger()
        ->addStatus($this
        ->t('New API key added to @app.', $args));
      $form_state
        ->setRedirectUrl($this
        ->getRedirectUrl());
    } catch (\Exception $exception) {
      $this
        ->messenger()
        ->addError($this
        ->t('Failed to add API key for @app.', $args));
    }
  }

  /**
   * Helper to find API products based on the recently active API key.
   *
   * @param \Drupal\apigee_edge\Entity\AppInterface $app
   *   The app entity.
   *
   * @return \Apigee\Edge\Structure\CredentialProductInterface[]|array
   *   An array of API products.
   */
  protected function getApiProductsForApp(AppInterface $app) : array {
    $approved_credentials = array_filter($app
      ->getCredentials(), function (AppCredentialInterface $credential) {
      return $credential
        ->getStatus() === AppCredentialInterface::STATUS_APPROVED;
    });

    // Find the recently active one.
    usort($approved_credentials, function (AppCredentialInterface $a, AppCredentialInterface $b) {
      return $a
        ->getIssuedAt() < $b
        ->getIssuedAt();
    });
    return count($approved_credentials) ? $approved_credentials[0]
      ->getApiProducts() : [];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AppApiKeyAddFormBase::$app protected property The app entity.
AppApiKeyAddFormBase::apiProductList abstract protected function Returns the list of API product that the user can see on the form.
AppApiKeyAddFormBase::appCredentialController abstract protected function Returns the app credential controller.
AppApiKeyAddFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 2
AppApiKeyAddFormBase::getApiProductsForApp protected function Helper to find API products based on the recently active API key.
AppApiKeyAddFormBase::getAppOwner abstract protected function Returns the app owner id. This needs to come from the route. 2
AppApiKeyAddFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AppApiKeyAddFormBase::getRedirectUrl abstract protected function Returns the redirect url for the app. 2
AppApiKeyAddFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AppApiKeyAddFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.