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

src/EventSubscriber/VariablesPlaceholderUrl.php
<?php

declare(strict_types=1);

namespace Drupal\component_library\EventSubscriber;

use Drupal\component_library\OverrideMode;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\component_library\Event\AddVariablesPlaceholderEvent;
use Drupal\component_library\Event\ReplaceVariablesPlaceholderEvent;

/**
 * Override mode config entity variable placeholders.
 */
final class VariablesPlaceholderUrl implements EventSubscriberInterface {

  private OverrideMode $overrideMode;

  public function __construct(OverrideMode $override_mode) {
    $this->overrideMode = $override_mode;
  }

  /**
   * {@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 Url) {
      if ($item->isRouted()) {
        $event->setPlaceholder([
          '#override_mode' => [
            '#type' => 'override_url',
            '#url_parts' => [
              'route_name' => $item->getRouteName(),
              'route_parameters' => $item->getRouteParameters(),
              'options' => $item->getOptions(),
            ],
          ],
        ]);
      }
    }
  }

  public function onReplaceVariablesPlaceholderEvent(ReplaceVariablesPlaceholderEvent $event): void {
    $config = $event->getConfig();
    if (isset($config['#url_parts']) && $config['#type'] == 'override_url') {
      foreach ($config['#url_parts'] as &$part) {
        if (is_array($part)) {
          $part = $this->overrideMode->replacePlaceholders($part);
        }
      }
      $url = new Url(
        $config['#url_parts']['route_name'],
        $config['#url_parts']['route_parameters'],
        $config['#url_parts']['options'],
      );
      $event->setReplacement($url);
    }
  }

}

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

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