Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / layout_builder / src / EventSubscriber / BlockComponentRenderArray.php
1 <?php
2
3 namespace Drupal\layout_builder\EventSubscriber;
4
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;
11
12 /**
13  * Builds render arrays and handles access for all block components.
14  *
15  * @internal
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.
19  */
20 class BlockComponentRenderArray implements EventSubscriberInterface {
21
22   /**
23    * The current user.
24    *
25    * @var \Drupal\Core\Session\AccountInterface
26    */
27   protected $currentUser;
28
29   /**
30    * Creates a BlockComponentRenderArray object.
31    *
32    * @param \Drupal\Core\Session\AccountInterface $current_user
33    *   The current user.
34    */
35   public function __construct(AccountInterface $current_user) {
36     $this->currentUser = $current_user;
37   }
38
39   /**
40    * {@inheritdoc}
41    */
42   public static function getSubscribedEvents() {
43     $events[LayoutBuilderEvents::SECTION_COMPONENT_BUILD_RENDER_ARRAY] = ['onBuildRender', 100];
44     return $events;
45   }
46
47   /**
48    * Builds render arrays for block plugins and sets it on the event.
49    *
50    * @param \Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent $event
51    *   The section component render event.
52    */
53   public function onBuildRender(SectionComponentBuildRenderArrayEvent $event) {
54     $block = $event->getPlugin();
55     if (!$block instanceof BlockPluginInterface) {
56       return;
57     }
58
59     // Only check access if the component is not being previewed.
60     if ($event->inPreview()) {
61       $access = AccessResult::allowed()->setCacheMaxAge(0);
62     }
63     else {
64       $access = $block->access($this->currentUser, TRUE);
65     }
66
67     $event->addCacheableDependency($access);
68     if ($access->isAllowed()) {
69       $event->addCacheableDependency($block);
70
71       $build = [
72         // @todo Move this to BlockBase in https://www.drupal.org/node/2931040.
73         '#theme' => 'block',
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(),
80       ];
81       $event->setBuild($build);
82     }
83   }
84
85 }