LayoutBuilderRestrictionsSubscriber.php in Layout Builder Restrictions 8
File
src/EventSubscriber/LayoutBuilderRestrictionsSubscriber.php
View source
<?php
namespace Drupal\layout_builder_restrictions\EventSubscriber;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\CurrentRouteMatch;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LayoutBuilderRestrictionsSubscriber implements EventSubscriberInterface {
protected $routeMatch;
protected $moduleHandler;
public function __construct(CurrentRouteMatch $route_match, ModuleHandlerInterface $handler) {
$this->routeMatch = $route_match;
$this->moduleHandler = $handler;
}
public function onKernelView(GetResponseForControllerResultEvent $event) {
$route_name = $this->routeMatch
->getCurrentRouteMatch()
->getRouteName();
$result = $event
->getControllerResult();
switch ($route_name) {
case 'layout_builder.choose_section':
$this
->alterLayoutChooser($result);
break;
case 'layout_builder.choose_block':
$this
->alterBlockChooser($result);
break;
default:
return;
}
$event
->setControllerResult($result);
}
protected function alterLayoutChooser(&$result) {
if (empty($result['layouts']['#items'])) {
return;
}
if (interface_exists('Drupal\\Core\\Plugin\\FilteredPluginManagerInterface')) {
return;
}
$keys = $this->moduleHandler
->invokeAll('layout_builder_restrictions_allowed_layouts');
$this->moduleHandler
->alter('layout_builder_restrictions_allowed_layouts', $keys);
if (!empty($keys)) {
foreach ($result['layouts']['#items'] as $delta => $item) {
$url = $item['#url'];
$params = $url
->getRouteParameters();
if (!in_array($params['plugin_id'], $keys)) {
unset($result['layouts']['#items'][$delta]);
}
}
}
}
protected function alterBlockChooser(array &$result) {
if (interface_exists('Drupal\\Core\\Plugin\\FilteredPluginManagerInterface')) {
$this->moduleHandler
->alter('layout_builder_restrictions_chooser_result', $result);
return;
}
$keys = $this->moduleHandler
->invokeAll('layout_builder_restrictions_allowed_block_keys');
if (!empty($keys)) {
$this->moduleHandler
->alter('layout_builder_restrictions_allowed_block_keys', $keys);
foreach (Element::children($result) as $delta) {
if (!in_array($delta, $keys)) {
$result[$delta]['#access'] = FALSE;
}
}
}
$this->moduleHandler
->alter('layout_builder_restrictions_chooser_result', $result);
}
public static function getSubscribedEvents() {
return [
KernelEvents::VIEW => [
'onKernelView',
1,
],
];
}
}