3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Drupal\Core\Routing\RouteBuildEvent;
7 use Drupal\Core\Routing\RoutingEvents;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9 use Symfony\Component\Routing\RouteCollection;
12 * Ensures that routes can be provided by entity types.
14 class EntityRouteProviderSubscriber implements EventSubscriberInterface {
19 * @var \Drupal\Core\Entity\EntityManagerInterface
21 protected $entityManager;
24 * Constructs a new EntityRouteProviderSubscriber instance.
26 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
29 public function __construct(EntityManagerInterface $entity_manager) {
30 $this->entityManager = $entity_manager;
34 * Provides routes on route rebuild time.
36 * @param \Drupal\Core\Routing\RouteBuildEvent $event
37 * The route build event.
39 public function onDynamicRouteEvent(RouteBuildEvent $event) {
40 $route_collection = $event->getRouteCollection();
41 foreach ($this->entityManager->getDefinitions() as $entity_type) {
42 if ($entity_type->hasRouteProviders()) {
43 foreach ($this->entityManager->getRouteProviders($entity_type->id()) as $route_provider) {
44 // Allow to both return an array of routes or a route collection,
45 // like route_callbacks in the routing.yml file.
47 $routes = $route_provider->getRoutes($entity_type);
48 if ($routes instanceof RouteCollection) {
49 $routes = $routes->all();
51 foreach ($routes as $route_name => $route) {
52 // Don't override existing routes.
53 if (!$route_collection->get($route_name)) {
54 $route_collection->add($route_name, $route);
65 public static function getSubscribedEvents() {
66 $events[RoutingEvents::DYNAMIC][] = ['onDynamicRouteEvent'];