TestPrepareLayout.php in Drupal 10
File
core/modules/layout_builder/tests/modules/layout_builder_element_test/src/EventSubscriber/TestPrepareLayout.php
View source
<?php
namespace Drupal\layout_builder_element_test\EventSubscriber;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\layout_builder\Event\PrepareLayoutEvent;
use Drupal\layout_builder\LayoutBuilderEvents;
use Drupal\layout_builder\LayoutTempstoreRepositoryInterface;
use Drupal\layout_builder\Section;
use Drupal\layout_builder\SectionComponent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TestPrepareLayout implements EventSubscriberInterface {
use StringTranslationTrait;
protected $layoutTempstoreRepository;
protected $messenger;
public function __construct(LayoutTempstoreRepositoryInterface $layout_tempstore_repository, MessengerInterface $messenger) {
$this->layoutTempstoreRepository = $layout_tempstore_repository;
$this->messenger = $messenger;
}
public static function getSubscribedEvents() : array {
$events[LayoutBuilderEvents::PREPARE_LAYOUT][] = [
'onBeforePrepareLayout',
20,
];
$events[LayoutBuilderEvents::PREPARE_LAYOUT][] = [
'onAfterPrepareLayout',
-10,
];
return $events;
}
public function onBeforePrepareLayout(PrepareLayoutEvent $event) {
$section_storage = $event
->getSectionStorage();
$context = $section_storage
->getContextValues();
if (!empty($context['entity'])) {
$entity = $context['entity'];
if (in_array($entity
->id(), [
'1',
'2',
])) {
$section = new Section('layout_onecol');
$section
->appendComponent(new SectionComponent('fake-uuid', 'content', [
'id' => 'static_block',
'label' => 'Test static block title',
'label_display' => 'visible',
'provider' => 'fake_provider',
]));
$section_storage
->appendSection($section);
}
if ($entity
->id() === '2') {
$event
->stopPropagation();
}
}
}
public function onAfterPrepareLayout(PrepareLayoutEvent $event) {
$section_storage = $event
->getSectionStorage();
$context = $section_storage
->getContextValues();
if (!empty($context['entity'])) {
$entity = $context['entity'];
if (in_array($entity
->id(), [
'1',
'2',
'3',
])) {
$section = new Section('layout_onecol');
$section
->appendComponent(new SectionComponent('fake-uuid', 'content', [
'id' => 'static_block_two',
'label' => 'Test second static block title',
'label_display' => 'visible',
'provider' => 'fake_provider',
]));
$section_storage
->appendSection($section);
}
}
}
}