ReadOnlyFormSubscriber.php in Configuration Read-only mode 8
File
src/EventSubscriber/ReadOnlyFormSubscriber.php
View source
<?php
namespace Drupal\config_readonly\EventSubscriber;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\config_readonly\ReadOnlyFormEvent;
use Drupal\config_readonly\ConfigReadonlyWhitelistTrait;
class ReadOnlyFormSubscriber implements EventSubscriberInterface {
use ConfigReadonlyWhitelistTrait;
public function __construct(ModuleHandlerInterface $module_handler) {
$this
->setModuleHandler($module_handler);
}
protected $readOnlyFormIds = [
'config_single_import_form',
'system_modules',
'system_modules_uninstall',
'user_admin_permissions',
];
public function onFormAlter(ReadOnlyFormEvent $event) {
$form_object = $event
->getFormState()
->getFormObject();
$mark_form_read_only = $form_object instanceof ConfigFormBase || $form_object instanceof ConfigEntityListBuilder;
if (!$mark_form_read_only) {
$mark_form_read_only = in_array($form_object
->getFormId(), $this->readOnlyFormIds);
}
if (!$mark_form_read_only && $form_object instanceof EntityFormInterface) {
$entity = $form_object
->getEntity();
$mark_form_read_only = $entity instanceof ConfigEntityInterface;
}
if ($mark_form_read_only && $form_object instanceof EntityFormInterface) {
$entity = $form_object
->getEntity();
$name = $entity
->getConfigDependencyName();
if ($this
->matchesWhitelistPattern($name)) {
$mark_form_read_only = FALSE;
}
}
if ($mark_form_read_only && $form_object instanceof ConfigFormBase) {
$editable_config = $this
->getEditableConfigNames($form_object);
if ($editable_config == array_filter($editable_config, [
$this,
'matchesWhitelistPattern',
])) {
$mark_form_read_only = FALSE;
}
}
if ($mark_form_read_only) {
$event
->markFormReadOnly();
}
}
public static function getSubscribedEvents() {
$events = [];
$events[ReadOnlyFormEvent::NAME][] = [
'onFormAlter',
200,
];
return $events;
}
protected function getEditableConfigNames(ConfigFormBase $form) {
$reflection = new \ReflectionMethod(get_class($form), 'getEditableConfigNames');
$reflection
->setAccessible(TRUE);
return $reflection
->invoke($form);
}
}