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

src/EventSubscriber/VariablesPlaceholderViewBuilder.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\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityViewBuilderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Override mode view builder variable placeholders.
 */
final class VariablesPlaceholderViewBuilder implements EventSubscriberInterface {

  private EntityTypeManagerInterface $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@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 EntityViewBuilderInterface) {
      $reflection = new \ReflectionClass($item);
      $property = $reflection->getProperty('entityTypeId');
      $property->setAccessible(TRUE);
      $entity_type_id = $property->getValue($item);
      $event->setPlaceholder([
        '#override_mode' => [
          '#type' => 'override_entity_view_builder',
          '#entity_type' => $entity_type_id,
        ],
      ]);
    }
  }

  public function onReplaceVariablesPlaceholderEvent(ReplaceVariablesPlaceholderEvent $event): void {
    $config = $event->getConfig();
    if (isset($config['#type']) && $config['#type'] === 'override_entity_view_builder') {
      $view_builder = $this->entityTypeManager->getViewBuilder($config['#entity_type']);
      $event->setReplacement($view_builder);
    }
  }

}

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

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