component_library-1.0.x-dev/src/EventSubscriber/VariablesPlaceholderContentEntity.php

src/EventSubscriber/VariablesPlaceholderContentEntity.php
<?php

declare(strict_types=1);

namespace Drupal\component_library\EventSubscriber;

use Drupal\component_library\Event\AddVariablesPlaceholderEvent;
use Drupal\component_library\Event\ReplaceVariablesPlaceholderEvent;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\layout_builder\Entity\SampleEntityGeneratorInterface;
use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Override mode content entity variable placeholders.
 */
final class VariablesPlaceholderContentEntity implements EventSubscriberInterface {

  private SampleEntityGeneratorInterface $sampleEntityGenerator;

  public function __construct(SampleEntityGeneratorInterface $sample_entity_generator) {
    $this->sampleEntityGenerator = $sample_entity_generator;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events = [];
    $events[AddVariablesPlaceholderEvent::class][] = ['onAddVariablesPlaceholder'];
    $events[ReplaceVariablesPlaceholderEvent::class][] = ['onReplaceVariablesPlaceholderEvent'];
    return $events;
  }

  public function onAddVariablesPlaceholder(AddVariablesPlaceholderEvent $event): void {
    $item = $event->getItem();
    if ($item instanceof ContentEntityInterface && !$item instanceof UserInterface) {
      $event->setPlaceholder([
        '#override_mode' => [
          '#type' => 'override_content_entity',
          '#entity_type' => $item->getEntityTypeId(),
          '#bundle' => $item->bundle(),
        ],
      ]);
    }
  }

  public function onReplaceVariablesPlaceholderEvent(ReplaceVariablesPlaceholderEvent $event): void {
    $config = $event->getConfig();
    if (isset($config['#type']) && $config['#type'] === 'override_content_entity') {
      $entity = $this->sampleEntityGenerator->get($config['#entity_type'], $config['#bundle']);

      $event->setReplacement($entity);
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc