RoutePathSubscriber.php 2.09 KB
Newer Older
1 2
<?php

3
namespace Drupal\tome_static\EventSubscriber;
4

5 6
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
7 8
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Url;
9 10
use Drupal\tome_static\Event\CollectPathsEvent;
use Drupal\tome_static\Event\TomeStaticEvents;
11 12 13 14
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Adds route paths to the list of paths to export.
15 16
 *
 * @internal
17 18 19 20 21 22 23 24 25 26
 */
class RoutePathSubscriber implements EventSubscriberInterface {

  /**
   * The route provider.
   *
   * @var \Drupal\Core\Routing\RouteProviderInterface
   */
  protected $routeProvider;

27 28 29 30 31 32 33
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

34 35 36 37 38
  /**
   * Constructs the RoutePathSubscriber object.
   *
   * @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
   *   The route provider.
39 40
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
41
   */
42
  public function __construct(RouteProviderInterface $route_provider, LanguageManagerInterface $language_manager) {
43
    $this->routeProvider = $route_provider;
44
    $this->languageManager = $language_manager;
45 46 47 48 49
  }

  /**
   * Reacts to a collect paths event.
   *
50
   * @param \Drupal\tome_static\Event\CollectPathsEvent $event
51 52 53
   *   The collect paths event.
   */
  public function collectPaths(CollectPathsEvent $event) {
54 55
    $language_none = $this->languageManager
      ->getLanguage(LanguageInterface::LANGCODE_NOT_APPLICABLE);
56 57
    foreach ($this->routeProvider->getAllRoutes() as $route_name => $route) {
      try {
58 59 60
        $url = Url::fromRoute($route_name, [], [
          'language' => $language_none,
        ]);
61 62
        $path = $url->toString();
        if ($path && $url->access()) {
63
          $event->addPath(parse_url($path, PHP_URL_PATH));
64 65 66 67 68 69 70 71 72 73 74
        }
      }
      catch (\Exception $e) {
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
75
    $events[TomeStaticEvents::COLLECT_PATHS][] = ['collectPaths'];
76 77 78 79
    return $events;
  }

}