comparison core/lib/Drupal/Core/EventSubscriber/EntityRouteProviderSubscriber.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children af1871eacc83
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\EventSubscriber;
4
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;
10
11 /**
12 * Ensures that routes can be provided by entity types.
13 */
14 class EntityRouteProviderSubscriber implements EventSubscriberInterface {
15
16 /**
17 * The entity manager.
18 *
19 * @var \Drupal\Core\Entity\EntityManagerInterface
20 */
21 protected $entityManager;
22
23 /**
24 * Constructs a new EntityRouteProviderSubscriber instance.
25 *
26 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
27 * The entity manager.
28 */
29 public function __construct(EntityManagerInterface $entity_manager) {
30 $this->entityManager = $entity_manager;
31 }
32
33 /**
34 * Provides routes on route rebuild time.
35 *
36 * @param \Drupal\Core\Routing\RouteBuildEvent $event
37 * The route build event.
38 */
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.
46
47 $routes = $route_provider->getRoutes($entity_type);
48 if ($routes instanceof RouteCollection) {
49 $routes = $routes->all();
50 }
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);
55 }
56 }
57 }
58 }
59 }
60 }
61
62 /**
63 * {@inheritdoc}
64 */
65 public static function getSubscribedEvents() {
66 $events[RoutingEvents::DYNAMIC][] = ['onDynamicRouteEvent'];
67 return $events;
68 }
69
70 }