PathSubscriber.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Path\AliasManagerInterface;
  4. use Drupal\Core\Path\CurrentPathStack;
  5. use Symfony\Component\HttpKernel\HttpKernelInterface;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  8. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. /**
  11. * Provides a path subscriber that converts path aliases.
  12. */
  13. class PathSubscriber implements EventSubscriberInterface {
  14. /**
  15. * The alias manager that caches alias lookups based on the request.
  16. *
  17. * @var \Drupal\Core\Path\AliasManagerInterface
  18. */
  19. protected $aliasManager;
  20. /**
  21. * The current path.
  22. *
  23. * @var \Drupal\Core\Path\CurrentPathStack
  24. */
  25. protected $currentPath;
  26. /**
  27. * Constructs a new PathSubscriber instance.
  28. *
  29. * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
  30. * The alias manager.
  31. * @param \Drupal\Core\Path\CurrentPathStack $current_path
  32. * The current path.
  33. */
  34. public function __construct(AliasManagerInterface $alias_manager, CurrentPathStack $current_path) {
  35. $this->aliasManager = $alias_manager;
  36. $this->currentPath = $current_path;
  37. }
  38. /**
  39. * Sets the cache key on the alias manager cache decorator.
  40. *
  41. * KernelEvents::CONTROLLER is used in order to be executed after routing.
  42. *
  43. * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event
  44. * The Event to process.
  45. */
  46. public function onKernelController(FilterControllerEvent $event) {
  47. // Set the cache key on the alias manager cache decorator.
  48. if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
  49. $this->aliasManager->setCacheKey(rtrim($this->currentPath->getPath($event->getRequest()), '/'));
  50. }
  51. }
  52. /**
  53. * Ensures system paths for the request get cached.
  54. */
  55. public function onKernelTerminate(PostResponseEvent $event) {
  56. $this->aliasManager->writeCache();
  57. }
  58. /**
  59. * Registers the methods in this class that should be listeners.
  60. *
  61. * @return array
  62. * An array of event listener definitions.
  63. */
  64. public static function getSubscribedEvents() {
  65. $events[KernelEvents::CONTROLLER][] = ['onKernelController', 200];
  66. $events[KernelEvents::TERMINATE][] = ['onKernelTerminate', 200];
  67. return $events;
  68. }
  69. }