36a3f7311709f3da641a93a7ba27018638c2ea71
[yaffs-website] / web / core / modules / rest / src / EventSubscriber / EntityResourcePostRouteSubscriber.php
1 <?php
2
3 namespace Drupal\rest\EventSubscriber;
4
5 use Drupal\Core\Entity\EntityTypeManagerInterface;
6 use Drupal\Core\Routing\RouteBuildEvent;
7 use Drupal\Core\Routing\RoutingEvents;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
10 /**
11  * Generates a 'create' route for an entity type if it has a REST POST route.
12  */
13 class EntityResourcePostRouteSubscriber implements EventSubscriberInterface {
14
15   /**
16    * The REST resource config storage.
17    *
18    * @var \Drupal\Core\Entity\EntityManagerInterface
19    */
20   protected $resourceConfigStorage;
21
22   /**
23    * Constructs a new EntityResourcePostRouteSubscriber instance.
24    *
25    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
26    *   The entity type manager.
27    */
28   public function __construct(EntityTypeManagerInterface $entity_type_manager) {
29     $this->resourceConfigStorage = $entity_type_manager->getStorage('rest_resource_config');
30   }
31
32   /**
33    * Provides routes on route rebuild time.
34    *
35    * @param \Drupal\Core\Routing\RouteBuildEvent $event
36    *   The route build event.
37    */
38   public function onDynamicRouteEvent(RouteBuildEvent $event) {
39     $route_collection = $event->getRouteCollection();
40
41     $resource_configs = $this->resourceConfigStorage->loadMultiple();
42     // Iterate over all REST resource config entities.
43     foreach ($resource_configs as $resource_config) {
44       // We only care about REST resource config entities for the
45       // \Drupal\rest\Plugin\rest\resource\EntityResource plugin.
46       $plugin_id = $resource_config->toArray()['plugin_id'];
47       if (substr($plugin_id, 0, 6) !== 'entity') {
48         continue;
49       }
50
51       $entity_type_id = substr($plugin_id, 7);
52       $rest_post_route_name = "rest.entity.$entity_type_id.POST";
53       if ($rest_post_route = $route_collection->get($rest_post_route_name)) {
54         // Create a route for the 'create' link relation type for this entity
55         // type that uses the same route definition as the REST 'POST' route
56         // which use that entity type.
57         // @see \Drupal\Core\Entity\Entity::toUrl()
58         $entity_create_route_name = "entity.$entity_type_id.create";
59         $route_collection->add($entity_create_route_name, $rest_post_route);
60       }
61     }
62   }
63
64   /**
65    * {@inheritdoc}
66    */
67   public static function getSubscribedEvents() {
68     // Priority -10, to run after \Drupal\rest\Routing\ResourceRoutes, which has
69     // priority 0.
70     $events[RoutingEvents::DYNAMIC][] = ['onDynamicRouteEvent', -10];
71     return $events;
72   }
73
74 }