<?php

declare(strict_types=1);

namespace Drupal\conductor\EventSubscriber;

use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Route;

/**
 * Affects only Conductor-owned routes.
 *
 * @internal
 */
final class ConductorRouteOptionsEventSubscriber implements EventSubscriberInterface {

  public function __construct() {}

  public function preventRouteNormalization(RouteBuildEvent $event): void {
    foreach ($event->getRouteCollection()->getIterator() as $route_name => $route) {
      assert($route instanceof Route);
      // This ensures our routing works with redirect module enabled.
      // @see \Drupal\conductor\PathProcessor\ConductorPathProcessor::processInbound.
      if (str_starts_with($route_name, 'conductor.proxy')) {
        $route->setDefault('_disable_route_normalizer', TRUE);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[RoutingEvents::ALTER][] = ['preventRouteNormalization'];
    return $events;
  }

}
