You are here

abstract class AppForm in Apigee Edge 8

Base entity form for developer- and team (company) app create/edit forms.

Hierarchy

Expanded class hierarchy of AppForm

File

src/Entity/Form/AppForm.php, line 38

Namespace

Drupal\apigee_edge\Entity\Form
View source
abstract class AppForm extends FieldableEdgeEntityForm {

  /**
   * Constructs AppCreationForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {

    // Ensure entity type manager is always initialized.
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $form['#tree'] = TRUE;

    /** @var \Drupal\apigee_edge\Entity\AppInterface $app */
    $app = $this->entity;

    // By default we render this as a simple text field, sub-classes can change
    // this.
    $form['owner'] = [
      '#title' => $this
        ->t('Owner'),
      '#description' => $this
        ->t("A developer's id (uuid), email address or a team's (company's) name."),
      '#type' => 'textfield',
      '#weight' => -100,
      '#default_value' => $app
        ->getAppOwner(),
      '#required' => TRUE,
    ];
    $form['name'] = [
      '#type' => 'machine_name',
      '#machine_name' => [
        'source' => [
          'displayName',
          'widget',
          0,
          'value',
        ],
        'label' => $this
          ->t('Internal name'),
        'exists' => [
          $this,
          'appExists',
        ],
      ],
      '#title' => $this
        ->t('Internal name'),
      // It should/can not be changed if app is not new.
      '#disabled' => !$app
        ->isNew(),
      '#default_value' => $app
        ->getName(),
    ];
    $form['#attached']['library'][] = 'apigee_edge/apigee_edge.components';
    $form['#attributes']['class'][] = 'apigee-edge--form';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->saveButtonLabel();
    return $actions;
  }

  /**
   * 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 label of the Save button on the form.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   *   The translatable label.
   */
  protected function saveButtonLabel() : TranslatableMarkup {
    return $this
      ->t('Save');
  }

  /**
   * {@inheritdoc}
   */
  public function buildEntity(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\apigee_edge\Entity\AppInterface $entity */
    $entity = parent::buildEntity($form, $form_state);

    // Set the owner of the app. Without this an app can not be saved.
    // @see \Drupal\apigee_edge\Entity\Controller\DeveloperAppEdgeEntityControllerProxy::create()
    $entity
      ->setAppOwner($form_state
      ->getValue('owner'));
    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\apigee_edge\Entity\AppInterface $app */
    $app = $this->entity;
    $was_new = $app
      ->isNew();
    $context = [
      '@app' => $this
        ->appEntityDefinition()
        ->getSingularLabel(),
      '@operation' => $was_new ? $this
        ->t('created') : $this
        ->t('updated'),
    ];

    // First save the app entity on Apigee Edge.
    $result = $this
      ->saveApp();
    if ($result > 0) {

      // Then apply credential changes on the app.
      $credential_save_result = $this
        ->saveAppCredentials($app, $form_state);

      // If credential save result is either successful (TRUE) or NULL
      // (no operation performed because there were no change in API product
      // association) then we consider the app save as successful.
      if ($credential_save_result ?? TRUE) {
        $this
          ->messenger()
          ->addStatus($this
          ->t('@app has been successfully @operation.', $context));

        // Also, if app credential(s) could be successfully saved as well then
        // display an extra confirmation message about this.
        if ($credential_save_result === TRUE) {
          $this
            ->messenger()
            ->addStatus($this
            ->t("Credential's product list has been successfully updated."));
        }

        // Only redirect the user from the add/edit form if all operations
        // could be successfully performed.
        $form_state
          ->setRedirectUrl($this
          ->getRedirectUrl());
      }
      else {

        // Display different error messages on app create/edit.
        if ($was_new) {
          $this
            ->messenger()
            ->addError($this
            ->t('Unable to set up credentials on the created app. Please try again.'));
        }
        else {
          $this
            ->messenger()
            ->addError($this
            ->t('Unable to update credentials on the app. Please try again.'));
        }
      }
    }
    else {
      $this
        ->messenger()
        ->addError($this
        ->t('@app could not be @operation. Please try again.', $context));
    }
    return $result;
  }

  /**
   * Saves the app entity on Apigee Edge.
   *
   * It should log failures but it should not display messages to users.
   * This is handled in save().
   *
   * @return int
   *   SAVED_NEW, SAVED_UPDATED or SAVED_UNKNOWN.
   */
  protected function saveApp() : int {

    /** @var \Drupal\apigee_edge\Entity\AppInterface $app */
    $app = $this->entity;
    $was_new = $app
      ->isNew();
    try {
      $result = $app
        ->save();
    } catch (EntityStorageException $exception) {
      $context = [
        '%app_name' => $app
          ->label(),
        '%owner' => $app
          ->getAppOwner(),
        '@app' => mb_strtolower($this
          ->appEntityDefinition()
          ->getSingularLabel()),
        '@owner' => mb_strtolower($this
          ->appOwnerEntityDefinition()
          ->getSingularLabel()),
        '@operation' => $was_new ? $this
          ->t('create') : $this
          ->t('update'),
      ];
      $context += Error::decodeException($exception);
      $this
        ->logger('apigee_edge')
        ->critical('Could not @operation %app_name @app of %owner @owner. @message %function (line %line of %file). <pre>@backtrace_string</pre>', $context);
      $result = EdgeEntityStorageBase::SAVED_UNKNOWN;
    }
    return $result;
  }

  /**
   * Save app credentials on Apigee Edge.
   *
   * It should log failures but it should not display messages to users.
   * This is handled in save().
   *
   * @param \Drupal\apigee_edge\Entity\AppInterface $app
   *   The app entity which credentials gets updated.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object with the credential related changes.
   *
   * @return bool|null
   *   TRUE on success, FALSE or failure, NULL if no action performed (because
   *   credentials did not change).
   */
  protected abstract function saveAppCredentials(AppInterface $app, FormStateInterface $form_state) : ?bool;

  /**
   * Returns the URL where the user should be redirected after form submission.
   *
   * @return \Drupal\Core\Url
   *   The redirect URL.
   */
  protected function getRedirectUrl() : Url {
    $entity = $this
      ->getEntity();
    if ($entity
      ->hasLinkTemplate('collection')) {

      // If available, return the collection URL.
      return $entity
        ->toUrl('collection');
    }
    else {

      // Otherwise fall back to the front page.
      return Url::fromRoute('<front>');
    }
  }

  /**
   * Returns the app specific 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 credential controller.
   */
  protected abstract function appCredentialController(string $owner, string $app_name) : AppCredentialControllerInterface;

  /**
   * Checks if the owner already has an app with the same name.
   *
   * @param string $name
   *   The app name.
   * @param array $element
   *   Form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   *
   * @return bool
   *   TRUE if the owner already has an app with the provided name or in case
   *   if an API communication error, FALSE otherwise.
   */
  public static abstract function appExists(string $name, array $element, FormStateInterface $form_state) : bool;

  /**
   * Returns the default lifetime of a created app credential.
   *
   * @return int
   *   App credential lifetime in seconds, 0 for never expire.
   */
  protected abstract function appCredentialLifeTime() : int;

  /**
   * Returns the developer/team (company) app entity definition.
   *
   * @return \Drupal\Core\Entity\EntityTypeInterface
   *   The app entity definition.
   */
  protected abstract function appEntityDefinition() : EntityTypeInterface;

  /**
   * Returns the app owner (developer or team (company)) entity definition.
   *
   * @return \Drupal\Core\Entity\EntityTypeInterface
   *   The app owner entity definition.
   */
  protected abstract function appOwnerEntityDefinition() : EntityTypeInterface;

  /**
   * {@inheritdoc}
   */
  public function getEntityFromRouteMatch(RouteMatchInterface $route_match, $entity_type_id) {

    // Always expect that the parameter in the route is not the entity type
    // (ex: {developer_app}) in case of apps rather just {app}.
    if ($route_match
      ->getRawParameter('app') !== NULL) {
      $entity = $route_match
        ->getParameter('app');
    }
    else {
      $entity = parent::getEntityFromRouteMatch($route_match, $entity_type_id);
    }
    return $entity;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AppForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions 1
AppForm::apiProductList abstract protected function Returns the list of API product that the user can see on the form.
AppForm::appCredentialController abstract protected function Returns the app specific app credential controller. 4
AppForm::appCredentialLifeTime abstract protected function Returns the default lifetime of a created app credential.
AppForm::appEntityDefinition abstract protected function Returns the developer/team (company) app entity definition.
AppForm::appExists abstract public static function Checks if the owner already has an app with the same name.
AppForm::appOwnerEntityDefinition abstract protected function Returns the app owner (developer or team (company)) entity definition.
AppForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity
AppForm::form public function Gets the actual form array to be built. Overrides FieldableEdgeEntityForm::form 2
AppForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityForm::getEntityFromRouteMatch
AppForm::getRedirectUrl protected function Returns the URL where the user should be redirected after form submission. 4
AppForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
AppForm::saveApp protected function Saves the app entity on Apigee Edge.
AppForm::saveAppCredentials abstract protected function Save app credentials on Apigee Edge. 2
AppForm::saveButtonLabel protected function Returns the label of the Save button on the form. 1
AppForm::__construct public function Constructs AppCreationForm. 2
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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
FieldableEdgeEntityForm::$entity protected property The fieldable entity being used by this form. Overrides EntityForm::$entity
FieldableEdgeEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
FieldableEdgeEntityForm::flagViolations protected function Flags violations for the current form.
FieldableEdgeEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form.
FieldableEdgeEntityForm::getFormDisplay public function Gets the form display. Overrides FieldableEdgeEntityFormInterface::getFormDisplay
FieldableEdgeEntityForm::init protected function Initialize the form state and the entity before the first form build. Overrides EntityForm::init
FieldableEdgeEntityForm::setFormDisplay public function Sets the form display. Overrides FieldableEdgeEntityFormInterface::setFormDisplay
FieldableEdgeEntityForm::validateForm public function TODO Add missing return type-hint in 2.x. Overrides FormBase::validateForm
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.