annotate core/modules/rest/src/RequestHandler.php @ 0:c75dbcec494b

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