EntityRouteProviderSubscriber.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Entity\EntityManagerInterface;
  4. use Drupal\Core\Routing\RouteBuildEvent;
  5. use Drupal\Core\Routing\RoutingEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Routing\RouteCollection;
  8. /**
  9. * Ensures that routes can be provided by entity types.
  10. */
  11. class EntityRouteProviderSubscriber implements EventSubscriberInterface {
  12. /**
  13. * The entity manager.
  14. *
  15. * @var \Drupal\Core\Entity\EntityManagerInterface
  16. */
  17. protected $entityManager;
  18. /**
  19. * Constructs a new EntityRouteProviderSubscriber instance.
  20. *
  21. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
  22. * The entity manager.
  23. */
  24. public function __construct(EntityManagerInterface $entity_manager) {
  25. $this->entityManager = $entity_manager;
  26. }
  27. /**
  28. * Provides routes on route rebuild time.
  29. *
  30. * @param \Drupal\Core\Routing\RouteBuildEvent $event
  31. * The route build event.
  32. */
  33. public function onDynamicRouteEvent(RouteBuildEvent $event) {
  34. $route_collection = $event->getRouteCollection();
  35. foreach ($this->entityManager->getDefinitions() as $entity_type) {
  36. if ($entity_type->hasRouteProviders()) {
  37. foreach ($this->entityManager->getRouteProviders($entity_type->id()) as $route_provider) {
  38. // Allow to both return an array of routes or a route collection,
  39. // like route_callbacks in the routing.yml file.
  40. $routes = $route_provider->getRoutes($entity_type);
  41. if ($routes instanceof RouteCollection) {
  42. $routes = $routes->all();
  43. }
  44. foreach ($routes as $route_name => $route) {
  45. // Don't override existing routes.
  46. if (!$route_collection->get($route_name)) {
  47. $route_collection->add($route_name, $route);
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public static function getSubscribedEvents() {
  58. $events[RoutingEvents::DYNAMIC][] = ['onDynamicRouteEvent'];
  59. return $events;
  60. }
  61. }