View source
<?php
namespace Drupal\restui\Form;
use Drupal\Core\Authentication\AuthenticationCollectorInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\rest\Plugin\ResourceInterface;
use Drupal\rest\RestResourceConfigInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\rest\Plugin\Type\ResourcePluginManager;
use Drupal\Core\Messenger\MessengerInterface;
class RestUIForm extends ConfigFormBase {
protected $moduleHandler;
protected $authenticationCollector;
protected $formats;
protected $resourcePluginManager;
protected $resourceConfigStorage;
protected $messenger;
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;
}
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'));
}
public function getFormId() {
return 'restui';
}
protected function getEditableConfigNames() {
return [
'rest.settings',
];
}
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;
}
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);
$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',
],
];
$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);
}
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',
],
];
$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,
];
$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;
}
protected function buildConfigurationFormForResourceGranularity(ResourceInterface $plugin, array $authentication_providers, array $format_options, array $config) {
$methods = $plugin
->availableMethods();
$method_options = array_combine($methods, $methods);
$form = [];
$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,
];
$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,
];
$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;
}
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);
}
}
protected function validateFormValuesForMethodGranularity(FormStateInterface $form_state) {
$method_checked = FALSE;
$methods = $form_state
->getValue([
'wrapper',
'methods',
]);
if (!empty($methods)) {
foreach ($methods as $method => $values) {
if ($values[$method]) {
$method_checked = TRUE;
$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'));
}
}
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'));
}
}
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.'));
$form_state
->setRedirect('restui.list');
}
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;
}
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;
}
public function processAjaxForm(array $form, FormStateInterface &$form_state) {
return $form['wrapper'];
}
}