AdminRouteSubscriber.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Drupal\system\EventSubscriber;
  3. use Drupal\Core\Routing\RouteSubscriberBase;
  4. use Drupal\Core\Routing\RoutingEvents;
  5. use Symfony\Component\Routing\Route;
  6. use Symfony\Component\Routing\RouteCollection;
  7. /**
  8. * Adds the _admin_route option to each admin HTML route.
  9. */
  10. class AdminRouteSubscriber extends RouteSubscriberBase {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. protected function alterRoutes(RouteCollection $collection) {
  15. foreach ($collection->all() as $route) {
  16. if (strpos($route->getPath(), '/admin') === 0 && !$route->hasOption('_admin_route') && static::isHtmlRoute($route)) {
  17. $route->setOption('_admin_route', TRUE);
  18. }
  19. }
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public static function getSubscribedEvents() {
  25. $events = parent::getSubscribedEvents();
  26. // Use a lower priority than \Drupal\field_ui\Routing\RouteSubscriber or
  27. // \Drupal\views\EventSubscriber\RouteSubscriber to ensure we add the option
  28. // to their routes.
  29. $events[RoutingEvents::ALTER] = ['onAlterRoutes', -200];
  30. return $events;
  31. }
  32. /**
  33. * Determines whether the given route is a HTML route.
  34. *
  35. * @param \Symfony\Component\Routing\Route $route
  36. * The route to analyze.
  37. *
  38. * @return bool
  39. * TRUE if HTML is a valid format for this route.
  40. */
  41. protected static function isHtmlRoute(Route $route) {
  42. // If a route has no explicit format, then HTML is valid.
  43. $format = $route->hasRequirement('_format') ? explode('|', $route->getRequirement('_format')) : ['html'];
  44. return in_array('html', $format, TRUE);
  45. }
  46. }