3 namespace Drupal\rest\EventSubscriber;
5 use Drupal\Core\Entity\EntityTypeManagerInterface;
6 use Drupal\Core\Routing\RouteBuildEvent;
7 use Drupal\Core\Routing\RoutingEvents;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
11 * Generates a 'create' route for an entity type if it has a REST POST route.
13 class EntityResourcePostRouteSubscriber implements EventSubscriberInterface {
16 * The REST resource config storage.
18 * @var \Drupal\Core\Entity\EntityManagerInterface
20 protected $resourceConfigStorage;
23 * Constructs a new EntityResourcePostRouteSubscriber instance.
25 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
26 * The entity type manager.
28 public function __construct(EntityTypeManagerInterface $entity_type_manager) {
29 $this->resourceConfigStorage = $entity_type_manager->getStorage('rest_resource_config');
33 * Provides routes on route rebuild time.
35 * @param \Drupal\Core\Routing\RouteBuildEvent $event
36 * The route build event.
38 public function onDynamicRouteEvent(RouteBuildEvent $event) {
39 $route_collection = $event->getRouteCollection();
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') {
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);
67 public static function getSubscribedEvents() {
68 // Priority -10, to run after \Drupal\rest\Routing\ResourceRoutes, which has
70 $events[RoutingEvents::DYNAMIC][] = ['onDynamicRouteEvent', -10];