3 namespace Drupal\layout_builder\EventSubscriber;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Block\BlockPluginInterface;
7 use Drupal\Core\Session\AccountInterface;
8 use Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent;
9 use Drupal\layout_builder\LayoutBuilderEvents;
10 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
13 * Builds render arrays and handles access for all block components.
16 * Layout Builder is currently experimental and should only be leveraged by
17 * experimental modules and development releases of contributed modules.
18 * See https://www.drupal.org/core/experimental for more information.
20 class BlockComponentRenderArray implements EventSubscriberInterface {
25 * @var \Drupal\Core\Session\AccountInterface
27 protected $currentUser;
30 * Creates a BlockComponentRenderArray object.
32 * @param \Drupal\Core\Session\AccountInterface $current_user
35 public function __construct(AccountInterface $current_user) {
36 $this->currentUser = $current_user;
42 public static function getSubscribedEvents() {
43 $events[LayoutBuilderEvents::SECTION_COMPONENT_BUILD_RENDER_ARRAY] = ['onBuildRender', 100];
48 * Builds render arrays for block plugins and sets it on the event.
50 * @param \Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent $event
51 * The section component render event.
53 public function onBuildRender(SectionComponentBuildRenderArrayEvent $event) {
54 $block = $event->getPlugin();
55 if (!$block instanceof BlockPluginInterface) {
59 // Only check access if the component is not being previewed.
60 if ($event->inPreview()) {
61 $access = AccessResult::allowed()->setCacheMaxAge(0);
64 $access = $block->access($this->currentUser, TRUE);
67 $event->addCacheableDependency($access);
68 if ($access->isAllowed()) {
69 $event->addCacheableDependency($block);
72 // @todo Move this to BlockBase in https://www.drupal.org/node/2931040.
74 '#configuration' => $block->getConfiguration(),
75 '#plugin_id' => $block->getPluginId(),
76 '#base_plugin_id' => $block->getBaseId(),
77 '#derivative_plugin_id' => $block->getDerivativeId(),
78 '#weight' => $event->getComponent()->getWeight(),
79 'content' => $block->build(),
81 $event->setBuild($build);