Commit 8a34a807 authored by s_leu's avatar s_leu Committed by Tim Bozeman
Browse files

Issue #3316106: Implemented an event subscriber that adds placeholder for URLs and replaces them

parent 97f796dd
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -101,3 +101,7 @@ services:
    class: Drupal\component_library\EventSubscriber\VariablesPlaceholderConfigEntity
    tags:
      - { name: event_subscriber }
  component_library.variables_placeholder.url:
    class: Drupal\component_library\EventSubscriber\VariablesPlaceholderUrl
    tags:
      - { name: event_subscriber }
+56 −0
Original line number Diff line number Diff line
<?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\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

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

  /**
   * {@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') {
      $event->setReplacement(new Url(
        $config['#url_parts']['route_name'],
        $config['#url_parts']['route_parameters'],
        $config['#url_parts']['options'],
      ));
    }
  }

}