You are here

class AuthenticationForm in Apigee Edge 8

Provides a form for saving the Apigee Edge API authentication key.

Hierarchy

Expanded class hierarchy of AuthenticationForm

1 file declares its use of AuthenticationForm
AuthenticationFormJsTest.php in tests/src/FunctionalJavascript/Form/AuthenticationFormJsTest.php
1 string reference to 'AuthenticationForm'
apigee_edge.routing.yml in ./apigee_edge.routing.yml
apigee_edge.routing.yml

File

src/Form/AuthenticationForm.php, line 35

Namespace

Drupal\apigee_edge\Form
View source
class AuthenticationForm extends KeyEditForm {

  /**
   * The config name that stores the authentication key entity id.
   *
   * @var string
   */
  public const CONFIG_NAME = 'apigee_edge.auth';

  /**
   * The default key entity id created by this form.
   *
   * @var string
   */
  public const DEFAULT_KEY_ENTITY_ID = 'apigee_edge_connection_default';

  /**
   * AuthenticationForm constructor.
   *
   * @param \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $key_storage
   *   The key storage.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(ConfigEntityStorageInterface $key_storage, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler) {
    parent::__construct($key_storage);
    $this->configFactory = $config_factory;

    // Module handler must be set but Key does not set it.
    $this->moduleHandler = $module_handler;

    // If we use `$this->config()`, config overrides won't be considered.
    $config = $config_factory
      ->get(static::CONFIG_NAME);

    // Loads to the key entity that belongs to the active key or creates a
    // new one _without_ saving it.
    if (!($active_key_id = $config
      ->get('active_key')) || !($active_key = $key_storage
      ->load($active_key_id))) {

      /** @var \Drupal\key\KeyInterface $active_key */
      $active_key = $key_storage
        ->create([
        'id' => static::DEFAULT_KEY_ENTITY_ID,
        'label' => $this
          ->t('Apigee Edge connection'),
        'description' => $this
          ->t('Contains the credentials for connecting to Apigee Edge.'),
        'key_type' => 'apigee_auth',
        'key_input' => 'apigee_auth_input',
        'key_provider' => 'apigee_edge_private_file',
      ]);
    }

    // Sets the entity object for the form. This is the best place where we
    // can do that if we do not want to override n+1 methods inherited from the
    // EntityForm.
    $this->entity = $active_key;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager')
      ->getStorage('key'), $container
      ->get('config.factory'), $container
      ->get('module_handler'));
  }

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

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

    // Do the same trick as Key does in its add form.
    // (Key should provide a "default" form that should be to handle
    // both key add and edit operations just like Node does.
    // Drupal\key\Form\KeyAddForm::buildForm()
    // Only when the form is first built.
    if ($this->entity
      ->isNew() && !$form_state
      ->isRebuilding()) {

      // Set the key value data to NULL, since this is a new key.
      $form_state
        ->set('key_value', [
        'original' => NULL,
        'processed_original' => NULL,
        'obscured' => NULL,
        'current' => '',
      ]);
    }

    // Hide the confirmation step added by Key.
    if (!$this->editConfirmed) {
      $this
        ->confirmEdit($form, $form_state);
      $form_state
        ->setRebuild(FALSE);
    }
    $form = parent::buildForm($form, $form_state);

    // Do not override title which is coming from the route.
    unset($form['#title']);

    // Hide fields that users should not be able to modify in this form.
    $form['label']['#access'] = FALSE;
    $form['id']['#access'] = FALSE;
    $form['description']['#access'] = FALSE;
    $form['settings']['type_section']['#access'] = FALSE;
    $form['settings']['input_section']['#title'] = $this
      ->t('Apigee Edge connection settings');
    $form['settings']['input_section']['#weight'] = 0;
    $form['settings']['provider_section']['#title'] = $this
      ->t('Advanced settings');

    // Provider selection should be closed by default unless the form rebuild
    // trigger by the provider selector or there is an error with the
    // key provider.

    /** @var \Drupal\apigee_edge\Plugin\KeyProviderRequirementsInterface $key_provider */
    $key_provider = $this->entity
      ->getKeyProvider();
    $key_provider_requirements_error = FALSE;

    // Warn user about key provider pre-requirement issues before form
    // submission.
    if ($key_provider instanceof KeyProviderRequirementsInterface) {
      try {
        $key_provider
          ->checkRequirements($this->entity);
      } catch (KeyProviderRequirementsException $exception) {
        $key_provider_requirements_error = TRUE;
        $form['settings']['provider_section']['key_provider']['#attributes']['class'][] = 'error';
      }
    }
    $form['settings']['provider_section']['#open'] = $key_provider_requirements_error || $form_state
      ->getTriggeringElement() && $form_state
      ->getTriggeringElement()['#name'] === 'key_provider';
    $form['settings']['provider_section']['#weight'] = $form['settings']['input_section']['#weight'] + 1;

    // Override the title of the submit button.
    $form['actions']['submit']['#value'] = $this
      ->t('Save configuration');

    // Hide the Delete button.
    $form['actions']['delete']['#access'] = FALSE;
    $form['#attached']['library'][] = 'apigee_edge/apigee_edge.admin';
    return $form;
  }

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

    // @see https://www.drupal.org/project/key/issues/3048562
    $status = parent::save($form, $form_state);

    // Save the authentication key entity id to module's configuration.
    $this->configFactory
      ->getEditable(static::CONFIG_NAME)
      ->set('active_key', $this->entity
      ->id())
      ->save();

    // Override the redirect destination.
    $form_state
      ->setRedirect('apigee_edge.settings');
    return $status;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AuthenticationForm::buildForm public function Form constructor. Overrides KeyEditForm::buildForm
AuthenticationForm::CONFIG_NAME public constant The config name that stores the authentication key entity id.
AuthenticationForm::create public static function Instantiates a new instance of this class. Overrides KeyFormBase::create
AuthenticationForm::DEFAULT_KEY_ENTITY_ID public constant The default key entity id created by this form.
AuthenticationForm::getFormId public function Returns a unique string identifying the form. Overrides EntityForm::getFormId
AuthenticationForm::save public function Form submission handler for the 'save' action. Overrides KeyFormBase::save
AuthenticationForm::__construct public function AuthenticationForm constructor. Overrides KeyFormBase::__construct
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::$entity protected property The entity being used by this form. 7
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::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
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::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
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::__get public function
EntityForm::__set public function
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::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.
KeyEditForm::$editConfirmed protected property Keeps track of extra confirmation step on key edit.
KeyEditForm::actions public function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
KeyEditForm::confirmEdit public function Submit handler for the edit confirmation button.
KeyEditForm::form public function Gets the actual form array to be built. Overrides KeyFormBase::form
KeyEditForm::validateForm public function Form validation handler. Overrides KeyFormBase::validateForm
KeyFormBase::$originalKey protected property The original key.
KeyFormBase::$storage protected property The key storage.
KeyFormBase::ajaxUpdateSettings public function AJAX callback to update the dynamic settings on the form.
KeyFormBase::createPluginFormState protected function Creates a FormStateInterface object for a plugin.
KeyFormBase::getOriginalKey public function Returns the original key entity.
KeyFormBase::moveFormStateErrors protected function Moves form errors from one form state to another.
KeyFormBase::moveFormStateStorage protected function Moves storage variables from one form state to another.
KeyFormBase::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 EntityForm::submitForm
KeyFormBase::updateKeyInput protected function Update the Key Input plugin.
KeyFormBase::updateKeyProvider protected function Update the Key Provider plugin.
KeyFormBase::updateKeyType protected function Update the Key Type plugin.
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.