RequestHandler.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace Drupal\rest;
  3. use Drupal\Component\Utility\ArgumentsResolver;
  4. use Drupal\Core\Cache\CacheableResponseInterface;
  5. use Drupal\Core\Config\ConfigFactoryInterface;
  6. use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  7. use Drupal\Core\Entity\EntityInterface;
  8. use Drupal\Core\Routing\RouteMatchInterface;
  9. use Drupal\rest\Plugin\ResourceInterface;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  13. use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
  14. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  15. use Symfony\Component\Serializer\Exception\InvalidArgumentException;
  16. use Symfony\Component\Serializer\SerializerInterface;
  17. /**
  18. * Acts as intermediate request forwarder for resource plugins.
  19. *
  20. * @see \Drupal\rest\EventSubscriber\ResourceResponseSubscriber
  21. */
  22. class RequestHandler implements ContainerInjectionInterface {
  23. /**
  24. * The config factory.
  25. *
  26. * @var \Drupal\Core\Config\ConfigFactoryInterface
  27. */
  28. protected $configFactory;
  29. /**
  30. * The serializer.
  31. *
  32. * @var \Symfony\Component\Serializer\SerializerInterface|\Symfony\Component\Serializer\Encoder\DecoderInterface
  33. */
  34. protected $serializer;
  35. /**
  36. * Creates a new RequestHandler instance.
  37. *
  38. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  39. * The config factory.
  40. * @param \Symfony\Component\Serializer\SerializerInterface|\Symfony\Component\Serializer\Encoder\DecoderInterface $serializer
  41. * The serializer.
  42. */
  43. public function __construct(ConfigFactoryInterface $config_factory, SerializerInterface $serializer) {
  44. $this->configFactory = $config_factory;
  45. $this->serializer = $serializer;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public static function create(ContainerInterface $container) {
  51. return new static(
  52. $container->get('config.factory'),
  53. $container->get('serializer')
  54. );
  55. }
  56. /**
  57. * Handles a REST API request.
  58. *
  59. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  60. * The route match.
  61. * @param \Symfony\Component\HttpFoundation\Request $request
  62. * The HTTP request object.
  63. * @param \Drupal\rest\RestResourceConfigInterface $_rest_resource_config
  64. * REST resource config entity ID.
  65. *
  66. * @return \Drupal\rest\ResourceResponseInterface|\Symfony\Component\HttpFoundation\Response
  67. * The REST resource response.
  68. */
  69. public function handle(RouteMatchInterface $route_match, Request $request, RestResourceConfigInterface $_rest_resource_config) {
  70. $response = $this->delegateToRestResourcePlugin($route_match, $request, $_rest_resource_config->getResourcePlugin());
  71. if ($response instanceof CacheableResponseInterface) {
  72. $response->addCacheableDependency($_rest_resource_config);
  73. // Add global rest settings config's cache tag, for BC flags.
  74. // @see \Drupal\rest\Plugin\rest\resource\EntityResource::permissions()
  75. // @see \Drupal\rest\EventSubscriber\RestConfigSubscriber
  76. // @todo Remove in https://www.drupal.org/node/2893804
  77. $response->addCacheableDependency($this->configFactory->get('rest.settings'));
  78. }
  79. return $response;
  80. }
  81. /**
  82. * Gets the normalized HTTP request method of the matched route.
  83. *
  84. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  85. * The route match.
  86. *
  87. * @return string
  88. * The normalized HTTP request method.
  89. */
  90. protected static function getNormalizedRequestMethod(RouteMatchInterface $route_match) {
  91. // Symfony is built to transparently map HEAD requests to a GET request. In
  92. // the case of the REST module's RequestHandler though, we essentially have
  93. // our own light-weight routing system on top of the Drupal/symfony routing
  94. // system. So, we have to respect the decision that the routing system made:
  95. // we look not at the request method, but at the route's method. All REST
  96. // routes are guaranteed to have _method set.
  97. // Response::prepare() will transform it to a HEAD response at the very last
  98. // moment.
  99. // @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
  100. // @see \Symfony\Component\Routing\Matcher\UrlMatcher::matchCollection()
  101. // @see \Symfony\Component\HttpFoundation\Response::prepare()
  102. $method = strtolower($route_match->getRouteObject()->getMethods()[0]);
  103. assert(count($route_match->getRouteObject()->getMethods()) === 1);
  104. return $method;
  105. }
  106. /**
  107. * Deserializes request body, if any.
  108. *
  109. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  110. * The route match.
  111. * @param \Symfony\Component\HttpFoundation\Request $request
  112. * The HTTP request object.
  113. * @param \Drupal\rest\Plugin\ResourceInterface $resource
  114. * The REST resource plugin.
  115. *
  116. * @return array|null
  117. * An object normalization, ikf there is a valid request body. NULL if there
  118. * is no request body.
  119. *
  120. * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
  121. * Thrown if the request body cannot be decoded.
  122. * @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException
  123. * Thrown if the request body cannot be denormalized.
  124. */
  125. protected function deserialize(RouteMatchInterface $route_match, Request $request, ResourceInterface $resource) {
  126. // Deserialize incoming data if available.
  127. $received = $request->getContent();
  128. $unserialized = NULL;
  129. if (!empty($received)) {
  130. $method = static::getNormalizedRequestMethod($route_match);
  131. $format = $request->getContentType();
  132. $definition = $resource->getPluginDefinition();
  133. // First decode the request data. We can then determine if the
  134. // serialized data was malformed.
  135. try {
  136. $unserialized = $this->serializer->decode($received, $format, ['request_method' => $method]);
  137. }
  138. catch (UnexpectedValueException $e) {
  139. // If an exception was thrown at this stage, there was a problem
  140. // decoding the data. Throw a 400 http exception.
  141. throw new BadRequestHttpException($e->getMessage());
  142. }
  143. // Then attempt to denormalize if there is a serialization class.
  144. if (!empty($definition['serialization_class'])) {
  145. try {
  146. $unserialized = $this->serializer->denormalize($unserialized, $definition['serialization_class'], $format, ['request_method' => $method]);
  147. }
  148. // These two serialization exception types mean there was a problem
  149. // with the structure of the decoded data and it's not valid.
  150. catch (UnexpectedValueException $e) {
  151. throw new UnprocessableEntityHttpException($e->getMessage());
  152. }
  153. catch (InvalidArgumentException $e) {
  154. throw new UnprocessableEntityHttpException($e->getMessage());
  155. }
  156. }
  157. }
  158. return $unserialized;
  159. }
  160. /**
  161. * Delegates an incoming request to the appropriate REST resource plugin.
  162. *
  163. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  164. * The route match.
  165. * @param \Symfony\Component\HttpFoundation\Request $request
  166. * The HTTP request object.
  167. * @param \Drupal\rest\Plugin\ResourceInterface $resource
  168. * The REST resource plugin.
  169. *
  170. * @return \Symfony\Component\HttpFoundation\Response|\Drupal\rest\ResourceResponseInterface
  171. * The REST resource response.
  172. */
  173. protected function delegateToRestResourcePlugin(RouteMatchInterface $route_match, Request $request, ResourceInterface $resource) {
  174. $unserialized = $this->deserialize($route_match, $request, $resource);
  175. $method = static::getNormalizedRequestMethod($route_match);
  176. // Determine the request parameters that should be passed to the resource
  177. // plugin.
  178. $argument_resolver = $this->createArgumentResolver($route_match, $unserialized, $request);
  179. try {
  180. $arguments = $argument_resolver->getArguments([$resource, $method]);
  181. }
  182. catch (\RuntimeException $exception) {
  183. @trigger_error('Passing in arguments the legacy way is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. Provide the right parameter names in the method, similar to controllers. See https://www.drupal.org/node/2894819', E_USER_DEPRECATED);
  184. $arguments = $this->getLegacyParameters($route_match, $unserialized, $request);
  185. }
  186. // Invoke the operation on the resource plugin.
  187. return call_user_func_array([$resource, $method], $arguments);
  188. }
  189. /**
  190. * Creates an argument resolver, containing all REST parameters.
  191. *
  192. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  193. * The route match.
  194. * @param mixed $unserialized
  195. * The unserialized data.
  196. * @param \Symfony\Component\HttpFoundation\Request $request
  197. * The request.
  198. *
  199. * @return \Drupal\Component\Utility\ArgumentsResolver
  200. * An instance of the argument resolver containing information like the
  201. * 'entity' we process and the 'unserialized' content from the request body.
  202. */
  203. protected function createArgumentResolver(RouteMatchInterface $route_match, $unserialized, Request $request) {
  204. $route = $route_match->getRouteObject();
  205. // Defaults for the parameters defined on the route object need to be added
  206. // to the raw arguments.
  207. $raw_route_arguments = $route_match->getRawParameters()->all() + $route->getDefaults();
  208. $route_arguments = $route_match->getParameters()->all();
  209. $upcasted_route_arguments = $route_arguments;
  210. // For request methods that have request bodies, ResourceInterface plugin
  211. // methods historically receive the unserialized request body as the N+1th
  212. // method argument, where N is the number of route parameters specified on
  213. // the accompanying route. To be able to use the argument resolver, which is
  214. // not based on position but on name and typehint, specify commonly used
  215. // names here. Similarly, those methods receive the original stored object
  216. // as the first method argument.
  217. $route_arguments_entity = NULL;
  218. // Try to find a parameter which is an entity.
  219. foreach ($route_arguments as $value) {
  220. if ($value instanceof EntityInterface) {
  221. $route_arguments_entity = $value;
  222. break;
  223. }
  224. }
  225. if (in_array($request->getMethod(), ['PATCH', 'POST'], TRUE)) {
  226. $upcasted_route_arguments['entity'] = $unserialized;
  227. $upcasted_route_arguments['data'] = $unserialized;
  228. $upcasted_route_arguments['unserialized'] = $unserialized;
  229. $upcasted_route_arguments['original_entity'] = $route_arguments_entity;
  230. }
  231. else {
  232. $upcasted_route_arguments['entity'] = $route_arguments_entity;
  233. }
  234. // Parameters which are not defined on the route object, but still are
  235. // essential for access checking are passed as wildcards to the argument
  236. // resolver.
  237. $wildcard_arguments = [$route, $route_match];
  238. $wildcard_arguments[] = $request;
  239. if (isset($unserialized)) {
  240. $wildcard_arguments[] = $unserialized;
  241. }
  242. return new ArgumentsResolver($raw_route_arguments, $upcasted_route_arguments, $wildcard_arguments);
  243. }
  244. /**
  245. * Provides the parameter usable without an argument resolver.
  246. *
  247. * This creates an list of parameters in a statically defined order.
  248. *
  249. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  250. * The route match
  251. * @param mixed $unserialized
  252. * The unserialized data.
  253. * @param \Symfony\Component\HttpFoundation\Request $request
  254. * The request.
  255. *
  256. * @deprecated in Drupal 8.4.0, will be removed before Drupal 9.0.0. Use the
  257. * argument resolver method instead, see ::createArgumentResolver().
  258. *
  259. * @see https://www.drupal.org/node/2894819
  260. *
  261. * @return array
  262. * An array of parameters.
  263. */
  264. protected function getLegacyParameters(RouteMatchInterface $route_match, $unserialized, Request $request) {
  265. $route_parameters = $route_match->getParameters();
  266. $parameters = [];
  267. // Filter out all internal parameters starting with "_".
  268. foreach ($route_parameters as $key => $parameter) {
  269. if ($key{0} !== '_') {
  270. $parameters[] = $parameter;
  271. }
  272. }
  273. return array_merge($parameters, [$unserialized, $request]);
  274. }
  275. }