You are here

abstract class OpenIDConnectClientFormBase in OpenID Connect / OAuth client 2.x

Form handler for the OpenID Connect client add and edit forms.

Hierarchy

Expanded class hierarchy of OpenIDConnectClientFormBase

File

src/Form/OpenIDConnectClientFormBase.php, line 22

Namespace

Drupal\openid_connect\Form
View source
abstract class OpenIDConnectClientFormBase extends EntityForm {

  /**
   * The plugin form manager.
   *
   * @var \Drupal\Core\Plugin\PluginFormFactoryInterface
   */
  protected $pluginFormFactory;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Constructs an OpenIDConnectClientFormBase object.
   *
   * @param \Drupal\Core\Plugin\PluginFormFactoryInterface $plugin_form_manager
   *   The plugin form manager.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   */
  public function __construct(PluginFormFactoryInterface $plugin_form_manager, LanguageManagerInterface $language_manager) {
    $this->pluginFormFactory = $plugin_form_manager;
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) : OpenIDConnectClientFormBase {
    return new static($container
      ->get('plugin_form.factory'), $container
      ->get('language_manager'));
  }

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

    /** @var \Drupal\openid_connect\Entity\OpenIDConnectClientEntity $entity */
    $entity = $this->entity;
    $form['#tree'] = TRUE;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#maxlength' => 255,
      '#default_value' => $entity
        ->label(),
      '#required' => TRUE,
    ];

    // If the entity is new, provide an AJAX-generated Redirect URL.
    if ($entity
      ->isNew()) {
      $form['label']['#ajax'] = [
        'callback' => '::changeRedirectUrl',
        'event' => 'focusout',
        'disable-refocus' => TRUE,
        'wrapper' => 'redirect-url-value',
      ];
    }
    $form['id'] = [
      '#type' => 'machine_name',
      '#title' => $this
        ->t('Machine name'),
      '#default_value' => $entity
        ->id(),
      '#machine_name' => [
        'exists' => [
          $this,
          'exists',
        ],
        'replace_pattern' => '([^a-z0-9_]+)|(^custom$)',
        'error' => 'The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".',
      ],
      '#disabled' => !$entity
        ->isNew(),
    ];
    $form['settings'] = [];
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $form['settings'] = $this
      ->getPluginForm($entity
      ->getPlugin())
      ->buildConfigurationForm($form['settings'], $subform_state);
    $form['redirect_url'] = [
      '#title' => $this
        ->t('Redirect URL'),
      '#type' => 'item',
      '#markup' => '<div id="redirect-url-value">' . $this
        ->getRedirectUrl($entity
        ->id()) . '</div>',
    ];
    return $form;
  }

  /**
   * Checks for an existing OpenID Connect client.
   *
   * @param string|int $entity_id
   *   The entity ID.
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return bool
   *   TRUE if this format already exists, FALSE otherwise.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function exists($entity_id, array $element, FormStateInterface $form_state) : bool {
    $result = $this->entityTypeManager
      ->getStorage('openid_connect_client')
      ->getQuery()
      ->condition('id', $element['#field_prefix'] . $entity_id)
      ->execute();
    return (bool) $result;
  }

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

    // Get validation status from the plugins.
    try {

      /** @var \Drupal\openid_connect\OpenIDConnectClientEntityInterface $entity */
      $entity = $this->entity;
      $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
      $this
        ->getPluginForm($entity
        ->getPlugin())
        ->validateConfigurationForm($form['settings'], $subform_state);
    } catch (InvalidPluginDefinitionException $e) {
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    // Set entity settings as configured.
    $values = $form_state
      ->getValues()['settings'];
    $this->entity
      ->set('settings', $values);

    // Call the plugin submit handler.
    try {

      /** @var \Drupal\openid_connect\OpenIDConnectClientEntityInterface $entity */
      $entity = $this->entity;
      $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
      $this
        ->getPluginForm($entity
        ->getPlugin())
        ->submitConfigurationForm($form, $subform_state);
    } catch (InvalidPluginDefinitionException $e) {
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) : int {
    $status = parent::save($form, $form_state);

    /** @var \Drupal\openid_connect\OpenIDConnectClientEntityInterface $entity */
    $entity = $this->entity;

    // Create an edit link.
    $edit_link = Link::fromTextAndUrl($this
      ->t('Edit'), $entity
      ->toUrl())
      ->toString();
    if ($status === SAVED_UPDATED) {

      // If we edited an existing entity...
      $this
        ->messenger()
        ->addMessage($this
        ->t('OpenID Connect client %label has been updated.', [
        '%label' => $entity
          ->label(),
      ]));
      $this
        ->logger('openid_connect')
        ->notice('OpenID Connect client %label has been updated.', [
        '%label' => $entity
          ->label(),
        'alink' => $edit_link,
      ]);
    }
    else {

      // If we created a new entity...
      $this
        ->messenger()
        ->addMessage($this
        ->t('OpenID Connect client %label has been added.', [
        '%label' => $entity
          ->label(),
      ]));
      $this
        ->logger('openid_connect')
        ->notice('OpenID Connect client %label has been added.', [
        '%label' => $entity
          ->label(),
        'alink' => $edit_link,
      ]);
    }
    $form_state
      ->setRedirect('entity.openid_connect_client.list');
    return $status;
  }

  /**
   * Retrieves the plugin form for a given OpenID connect client.
   *
   * @param \Drupal\openid_connect\Plugin\OpenIDConnectClientInterface $openid_client
   *   The OpenID Connect client plugin.
   *
   * @return \Drupal\Core\Plugin\PluginFormInterface
   *   The plugin form for the OpenID Connect client.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   */
  protected function getPluginForm(OpenIDConnectClientInterface $openid_client) : ?PluginFormInterface {
    if ($openid_client instanceof PluginWithFormsInterface) {
      return $this->pluginFormFactory
        ->createInstance($openid_client, 'configure');
    }
    return NULL;
  }

  /**
   * Returns the redirect URL.
   *
   * @param string|null $id
   *   Route parameter ID.
   *
   * @return string
   *   The absolute URL as a string.
   */
  public function getRedirectUrl($id = '') : string {
    if ($id) {
      $route_parameters = [
        'openid_connect_client' => $id,
      ];
      return Url::fromRoute('openid_connect.redirect_controller_redirect', $route_parameters, [
        'absolute' => TRUE,
        'language' => $this->languageManager
          ->getLanguage(LanguageInterface::LANGCODE_NOT_APPLICABLE),
      ])
        ->toString();
    }
    return $this
      ->t('Pending name input');
  }

  /**
   * AJAX callback to provide an updated Redirect URL when label is changed.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   Render array with the redirect URL.
   */
  public function changeRedirectUrl(array &$form, FormStateInterface $form_state) : array {
    return [
      '#markup' => '<div id="redirect-url-value">' . $this
        ->getRedirectUrl($form_state
        ->getValue('id')) . '</div>',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 11
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::actions protected function Returns an array of supported actions for the current entity form. 35
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 3
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 9
EntityForm::form public function Gets the actual form array to be built. 36
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
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 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
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::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
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
OpenIDConnectClientFormBase::$languageManager protected property The language manager.
OpenIDConnectClientFormBase::$pluginFormFactory protected property The plugin form manager.
OpenIDConnectClientFormBase::buildForm public function Form constructor. Overrides EntityForm::buildForm
OpenIDConnectClientFormBase::changeRedirectUrl public function AJAX callback to provide an updated Redirect URL when label is changed.
OpenIDConnectClientFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
OpenIDConnectClientFormBase::exists public function Checks for an existing OpenID Connect client.
OpenIDConnectClientFormBase::getPluginForm protected function Retrieves the plugin form for a given OpenID connect client.
OpenIDConnectClientFormBase::getRedirectUrl public function Returns the redirect URL.
OpenIDConnectClientFormBase::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
OpenIDConnectClientFormBase::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
OpenIDConnectClientFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
OpenIDConnectClientFormBase::__construct public function Constructs an OpenIDConnectClientFormBase object.
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. 4
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.