You are here

class RestUIForm in REST UI 8

Provides a REST resource configuration form.

Hierarchy

Expanded class hierarchy of RestUIForm

1 string reference to 'RestUIForm'
restui.routing.yml in ./restui.routing.yml
restui.routing.yml

File

src/Form/RestUIForm.php, line 21

Namespace

Drupal\restui\Form
View source
class RestUIForm extends ConfigFormBase {

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandler
   */
  protected $moduleHandler;

  /**
   * The authentication collector.
   *
   * @var \Drupal\Core\Authentication\AuthenticationCollectorInterface
   */
  protected $authenticationCollector;

  /**
   * The available serialization formats.
   *
   * @var array
   */
  protected $formats;

  /**
   * The REST plugin manager.
   *
   * @var \Drupal\rest\Plugin\Type\ResourcePluginManager
   */
  protected $resourcePluginManager;

  /**
   * The REST resource config storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $resourceConfigStorage;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a \Drupal\user\RestForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   *   The module handler.
   * @param \Drupal\Core\Authentication\AuthenticationCollectorInterface $authentication_collector
   *   The authentication collector.
   * @param array $formats
   *   The available serialization formats.
   * @param \Drupal\rest\Plugin\Type\ResourcePluginManager $resourcePluginManager
   *   The REST plugin manager.
   * @param \Drupal\Core\Entity\EntityStorageInterface $resource_config_storage
   *   The REST resource config storage.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ModuleHandler $module_handler, AuthenticationCollectorInterface $authentication_collector, array $formats, ResourcePluginManager $resourcePluginManager, EntityStorageInterface $resource_config_storage, MessengerInterface $messenger) {
    parent::__construct($config_factory);
    $this->moduleHandler = $module_handler;
    $this->authenticationCollector = $authentication_collector;
    $this->formats = $formats;
    $this->resourcePluginManager = $resourcePluginManager;
    $this->resourceConfigStorage = $resource_config_storage;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('module_handler'), $container
      ->get('authentication_collector'), $container
      ->getParameter('serializer.formats'), $container
      ->get('plugin.manager.rest'), $container
      ->get('entity_type.manager')
      ->getStorage('rest_resource_config'), $container
      ->get('messenger'));
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'rest.settings',
    ];
  }

  /**
   * Gets a REST resource config's granularity: from the form, otherwise config.
   *
   * @param string $id
   *   A REST resource config entity ID.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return string
   *   Either:
   *   - \Drupal\rest\RestResourceConfigInterface::METHOD_GRANULARITY
   *   - \Drupal\rest\RestResourceConfigInterface::RESOURCE_GRANULARITY
   */
  protected function getGranularity($id, FormStateInterface $form_state) {
    $granularity = $this
      ->config("rest.resource.{$id}")
      ->get('granularity');
    if ($form_state
      ->hasValue('granularity')) {
      $granularity = $form_state
        ->getValue('granularity');
    }
    if ($granularity === NULL) {
      $granularity = RestResourceConfigInterface::RESOURCE_GRANULARITY;
    }
    return $granularity;
  }

  /**
   * {@inheritdoc}
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param string $resource_id
   *   A string that identifies the REST resource.
   *
   * @return array
   *   The form structure.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   When no plugin found.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $resource_id = NULL) {
    $plugin = $this->resourcePluginManager
      ->createInstance($resource_id);
    if (empty($plugin)) {
      throw new NotFoundHttpException();
    }
    $id = str_replace(':', '.', $resource_id);
    $config = $this
      ->config("rest.resource.{$id}")
      ->get('configuration') ?: [];
    $pluginDefinition = $plugin
      ->getPluginDefinition();
    $form['#title'] = $this
      ->t('Settings for resource %label', [
      '%label' => $pluginDefinition['label'],
    ]);
    $form['#tree'] = TRUE;
    $form['resource_id'] = [
      '#type' => 'value',
      '#value' => $resource_id,
    ];
    $authentication_providers = array_keys($this->authenticationCollector
      ->getSortedProviders());
    $authentication_providers = array_combine($authentication_providers, $authentication_providers);
    $format_options = array_combine($this->formats, $this->formats);
    $granularity = $this
      ->getGranularity($id, $form_state);

    // Granularity selection.
    $form['granularity'] = [
      '#title' => $this
        ->t('Granularity'),
      '#type' => 'select',
      '#options' => [
        RestResourceConfigInterface::RESOURCE_GRANULARITY => $this
          ->t('Resource'),
        RestResourceConfigInterface::METHOD_GRANULARITY => $this
          ->t('Method'),
      ],
      '#default_value' => $granularity,
      '#ajax' => [
        'callback' => '::processAjaxForm',
        'wrapper' => 'wrapper',
      ],
    ];

    // Wrapper for ajax callback.
    $form['wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'wrapper',
      ],
    ];
    $form['wrapper'] += $granularity === RestResourceConfigInterface::RESOURCE_GRANULARITY ? $this
      ->buildConfigurationFormForResourceGranularity($plugin, $authentication_providers, $format_options, $config) : $this
      ->buildConfigurationFormForMethodGranularity($plugin, $authentication_providers, $format_options, $config);
    return parent::buildForm($form, $form_state);
  }

  /**
   * Subform constructor when the selected granularity is 'method'.
   *
   * @param \Drupal\rest\Plugin\ResourceInterface $plugin
   *   The REST Resource plugin being configured.
   * @param array $authentication_providers
   *   All available authentication providers, to use for #options.
   * @param array $format_options
   *   All available formats, to use for #options.
   * @param array $config
   *   The current configuration for the REST Resource config entity, or the
   *   empty array if it does not yet exist.
   *
   * @return array
   *   The subform structure.
   */
  protected function buildConfigurationFormForMethodGranularity(ResourceInterface $plugin, array $authentication_providers, array $format_options, array $config) {
    $methods = $plugin
      ->availableMethods();
    $form = [];
    foreach ($methods as $method) {
      $group = [];
      $group[$method] = [
        '#title' => $method,
        '#type' => 'checkbox',
        '#default_value' => isset($config[$method]),
      ];
      $group['settings'] = [
        '#type' => 'container',
        '#attributes' => [
          'style' => 'padding-left:20px',
        ],
      ];

      // Available request formats.
      $enabled_formats = [];
      if (isset($config[$method]['supported_formats'])) {
        $enabled_formats = $config[$method]['supported_formats'];
      }
      $method_checkbox_selector = ':input[name="wrapper[methods][' . $method . '][' . $method . ']"]';
      $states_show_if_method_is_enabled = [
        'visible' => [
          $method_checkbox_selector => [
            'checked' => TRUE,
          ],
        ],
        'invisible' => [
          $method_checkbox_selector => [
            'checked' => FALSE,
          ],
        ],
      ];
      $group['settings']['formats'] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Accepted request formats'),
        '#options' => $format_options,
        '#default_value' => $enabled_formats,
        '#states' => $states_show_if_method_is_enabled,
      ];

      // Authentication providers.
      $enabled_auth = [];
      if (isset($config[$method]['supported_auth'])) {
        $enabled_auth = $config[$method]['supported_auth'];
      }
      $group['settings']['auth'] = [
        '#title' => $this
          ->t('Authentication providers'),
        '#type' => 'checkboxes',
        '#options' => $authentication_providers,
        '#default_value' => $enabled_auth,
        '#states' => $states_show_if_method_is_enabled,
      ];
      $form['methods'][$method] = $group;
    }
    return $form;
  }

  /**
   * Subform constructor when the selected granularity is 'resource'.
   *
   * @param \Drupal\rest\Plugin\ResourceInterface $plugin
   *   The REST Resource plugin being configured.
   * @param array $authentication_providers
   *   All available authentication providers, to use for #options.
   * @param array $format_options
   *   All available formats, to use for #options.
   * @param array $config
   *   The current configuration for the REST Resource config entity, or the
   *   empty array if it does not yet exist.
   *
   * @return array
   *   The subform structure.
   */
  protected function buildConfigurationFormForResourceGranularity(ResourceInterface $plugin, array $authentication_providers, array $format_options, array $config) {
    $methods = $plugin
      ->availableMethods();
    $method_options = array_combine($methods, $methods);
    $form = [];

    // Methods.
    $enabled_methods = [];
    foreach ($methods as $method) {
      if (isset($config['methods']) && in_array($method, $config['methods'])) {
        $enabled_methods[$method] = $method;
      }
    }
    $form['settings']['methods'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Methods'),
      '#options' => $method_options,
      '#default_value' => $enabled_methods,
    ];

    // Formats.
    $enabled_formats = [];
    if (isset($config['formats'])) {
      $enabled_formats = $config['formats'];
    }
    $form['settings']['formats'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Accepted request formats'),
      '#options' => $format_options,
      '#default_value' => $enabled_formats,
    ];

    // Authentication providers.
    $enabled_auth = [];
    if (isset($config['authentication'])) {
      $enabled_auth = $config['authentication'];
    }
    $form['settings']['authentication'] = [
      '#title' => $this
        ->t('Authentication providers'),
      '#type' => 'checkboxes',
      '#options' => $authentication_providers,
      '#default_value' => $enabled_auth,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * @see \Drupal\rest\Routing\ResourceRoutes::alterRoutes()
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getValue('granularity') === RestResourceConfigInterface::RESOURCE_GRANULARITY) {
      $this
        ->validateFormValuesForResourceGranularity($form_state);
    }
    else {
      $this
        ->validateFormValuesForMethodGranularity($form_state);
    }
  }

  /**
   * Form validation handler when the selected granularity is 'method'.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @see \Drupal\restui\Form\RestUIForm::validateForm()
   */
  protected function validateFormValuesForMethodGranularity(FormStateInterface $form_state) {

    // At least one method must be checked.
    $method_checked = FALSE;
    $methods = $form_state
      ->getValue([
      'wrapper',
      'methods',
    ]);
    if (!empty($methods)) {
      foreach ($methods as $method => $values) {
        if ($values[$method]) {
          $method_checked = TRUE;

          // At least one format and authentication provider must be selected.
          $formats = array_filter($values['settings']['formats']);
          if (empty($formats)) {
            $form_state
              ->setErrorByName('methods][' . $method . '][settings][formats', $this
              ->t('At least one format must be selected for method @method.', [
              '@method' => $method,
            ]));
          }
          $auth = array_filter($values['settings']['auth']);
          if (empty($auth)) {
            $form_state
              ->setErrorByName('methods][' . $method . '][settings][auth', $this
              ->t('At least one authentication provider must be selected for method @method.', [
              '@method' => $method,
            ]));
          }
        }
      }
    }
    if (!$method_checked) {
      $form_state
        ->setErrorByName('methods', $this
        ->t('At least one HTTP method must be selected'));
    }
  }

  /**
   * Form validation handler when the selected granularity is 'resource'.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @see \Drupal\restui\Form\RestUIForm::validateForm()
   */
  protected function validateFormValuesForResourceGranularity(FormStateInterface $form_state) {
    $settings = $form_state
      ->getValue([
      'wrapper',
      'settings',
    ]);
    if (empty($settings) || empty(array_filter($settings['methods']))) {
      $form_state
        ->setErrorByName('methods', $this
        ->t('At least one HTTP method must be selected.'));
    }
    if (empty($settings) || empty(array_filter($settings['formats']))) {
      $form_state
        ->setErrorByName('formats', $this
        ->t('At least one request format must be selected.'));
    }
    if (empty($settings) || empty(array_filter($settings['authentication']))) {
      $form_state
        ->setErrorByName('authentication', $this
        ->t('At least one authentication provider must be selected'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $resource_id = str_replace(':', '.', $form_state
      ->getValue('resource_id'));
    $config = $this->resourceConfigStorage
      ->load($resource_id);
    $granularity = $form_state
      ->getValue('granularity');
    if (!$config) {
      $config = $this->resourceConfigStorage
        ->create([
        'id' => $resource_id,
      ]);
    }
    $configuration = $granularity === RestResourceConfigInterface::RESOURCE_GRANULARITY ? static::getConfigurationForResourceGranularity($form_state) : static::getConfigurationForMethodGranularity($form_state);
    $config
      ->set('granularity', $granularity);
    $config
      ->set('configuration', $configuration);
    $config
      ->enable();
    $config
      ->save();
    $this->messenger
      ->addStatus($this
      ->t('The resource has been updated.'));

    // Redirect back to the listing.
    $form_state
      ->setRedirect('restui.list');
  }

  /**
   * Calculates the REST resource configuration when granularity is 'method'.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The value for the 'configuration' key in a REST Resource config entity.
   */
  protected static function getConfigurationForMethodGranularity(FormStateInterface $form_state) {
    $configuration = [];
    $methods = $form_state
      ->getValue([
      'wrapper',
      'methods',
    ]);
    foreach ($methods as $method => $settings) {
      if ($settings[$method]) {
        $configuration[$method] = [
          'supported_formats' => array_keys(array_filter($settings['settings']['formats'])),
          'supported_auth' => array_keys(array_filter($settings['settings']['auth'])),
        ];
      }
      else {
        unset($configuration[$method]);
      }
    }
    return $configuration;
  }

  /**
   * Calculates the REST resource configuration when granularity is 'resource'.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The value for the 'configuration' key in a REST Resource config entity.
   */
  protected static function getConfigurationForResourceGranularity(FormStateInterface $form_state) {
    $settings = $form_state
      ->getValue([
      'wrapper',
      'settings',
    ]);
    $configuration = [
      'methods' => array_keys(array_filter($settings['methods'])),
      'formats' => array_keys(array_filter($settings['formats'])),
      'authentication' => array_keys(array_filter($settings['authentication'])),
    ];
    return $configuration;
  }

  /**
   * Return the settings part of the form when rebuilding through ajax.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return array
   */
  public function processAjaxForm(array $form, FormStateInterface &$form_state) {
    return $form['wrapper'];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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.
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 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.
RestUIForm::$authenticationCollector protected property The authentication collector.
RestUIForm::$formats protected property The available serialization formats.
RestUIForm::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
RestUIForm::$moduleHandler protected property The module handler.
RestUIForm::$resourceConfigStorage protected property The REST resource config storage.
RestUIForm::$resourcePluginManager protected property The REST plugin manager.
RestUIForm::buildConfigurationFormForMethodGranularity protected function Subform constructor when the selected granularity is 'method'.
RestUIForm::buildConfigurationFormForResourceGranularity protected function Subform constructor when the selected granularity is 'resource'.
RestUIForm::buildForm public function Overrides ConfigFormBase::buildForm
RestUIForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
RestUIForm::getConfigurationForMethodGranularity protected static function Calculates the REST resource configuration when granularity is 'method'.
RestUIForm::getConfigurationForResourceGranularity protected static function Calculates the REST resource configuration when granularity is 'resource'.
RestUIForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
RestUIForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RestUIForm::getGranularity protected function Gets a REST resource config's granularity: from the form, otherwise config.
RestUIForm::processAjaxForm public function Return the settings part of the form when rebuilding through ajax.
RestUIForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
RestUIForm::validateForm public function Overrides FormBase::validateForm
RestUIForm::validateFormValuesForMethodGranularity protected function Form validation handler when the selected granularity is 'method'.
RestUIForm::validateFormValuesForResourceGranularity protected function Form validation handler when the selected granularity is 'resource'.
RestUIForm::__construct public function Constructs a \Drupal\user\RestForm object. Overrides ConfigFormBase::__construct
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.