annotate core/modules/jsonapi/src/Revisions/ResourceVersionRouteEnhancer.php @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents
children
rev   line source
Chris@5 1 <?php
Chris@5 2
Chris@5 3 namespace Drupal\jsonapi\Revisions;
Chris@5 4
Chris@5 5 use Drupal\Core\Cache\CacheableMetadata;
Chris@5 6 use Drupal\Core\Entity\EntityInterface;
Chris@5 7 use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
Chris@5 8 use Drupal\Core\Http\Exception\CacheableHttpException;
Chris@5 9 use Drupal\Core\Routing\EnhancerInterface;
Chris@5 10 use Drupal\jsonapi\Routing\Routes;
Chris@5 11 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
Chris@5 12 use Symfony\Component\HttpFoundation\Request;
Chris@5 13 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
Chris@5 14
Chris@5 15 /**
Chris@5 16 * Loads an appropriate revision for the requested resource version.
Chris@5 17 *
Chris@5 18 * @internal JSON:API maintains no PHP API since its API is the HTTP API. This
Chris@5 19 * class may change at any time and this will break any dependencies on it.
Chris@5 20 *
Chris@5 21 * @see https://www.drupal.org/project/jsonapi/issues/3032787
Chris@5 22 * @see jsonapi.api.php
Chris@5 23 */
Chris@5 24 final class ResourceVersionRouteEnhancer implements EnhancerInterface {
Chris@5 25
Chris@5 26 /**
Chris@5 27 * The route default parameter name.
Chris@5 28 *
Chris@5 29 * @var string
Chris@5 30 */
Chris@5 31 const REVISION_ID_KEY = 'revision_id';
Chris@5 32
Chris@5 33 /**
Chris@5 34 * The query parameter for providing a version (revision) value.
Chris@5 35 *
Chris@5 36 * @var string
Chris@5 37 */
Chris@5 38 const RESOURCE_VERSION_QUERY_PARAMETER = 'resourceVersion';
Chris@5 39
Chris@5 40 /**
Chris@5 41 * A route parameter key which indicates that working copies were requested.
Chris@5 42 *
Chris@5 43 * @var string
Chris@5 44 */
Chris@5 45 const WORKING_COPIES_REQUESTED = 'working_copies_requested';
Chris@5 46
Chris@5 47 /**
Chris@5 48 * The cache context by which vary the loaded entity revision.
Chris@5 49 *
Chris@5 50 * @var string
Chris@5 51 *
Chris@5 52 * @todo When D8 requires PHP >=5.6, convert to expression using the RESOURCE_VERSION_QUERY_PARAMETER constant.
Chris@5 53 */
Chris@5 54 const CACHE_CONTEXT = 'url.query_args:resourceVersion';
Chris@5 55
Chris@5 56 /**
Chris@5 57 * Resource version validation regex.
Chris@5 58 *
Chris@5 59 * @var string
Chris@5 60 *
Chris@5 61 * @todo When D8 requires PHP >=5.6, convert to expression using the VersionNegotiator::SEPARATOR constant.
Chris@5 62 */
Chris@5 63 const VERSION_IDENTIFIER_VALIDATOR = '/^[a-z]+[a-z_]*[a-z]+:[a-zA-Z0-9\-]+(:[a-zA-Z0-9\-]+)*$/';
Chris@5 64
Chris@5 65 /**
Chris@5 66 * The revision ID negotiator.
Chris@5 67 *
Chris@5 68 * @var \Drupal\jsonapi\Revisions\VersionNegotiator
Chris@5 69 */
Chris@5 70 protected $versionNegotiator;
Chris@5 71
Chris@5 72 /**
Chris@5 73 * ResourceVersionRouteEnhancer constructor.
Chris@5 74 *
Chris@5 75 * @param \Drupal\jsonapi\Revisions\VersionNegotiator $version_negotiator_manager
Chris@5 76 * The version negotiator.
Chris@5 77 */
Chris@5 78 public function __construct(VersionNegotiator $version_negotiator_manager) {
Chris@5 79 $this->versionNegotiator = $version_negotiator_manager;
Chris@5 80 }
Chris@5 81
Chris@5 82 /**
Chris@5 83 * {@inheritdoc}
Chris@5 84 */
Chris@5 85 public function enhance(array $defaults, Request $request) {
Chris@5 86 if (!Routes::isJsonApiRequest($defaults) || !($resource_type = Routes::getResourceTypeNameFromParameters($defaults))) {
Chris@5 87 return $defaults;
Chris@5 88 }
Chris@5 89
Chris@5 90 $has_version_param = $request->query->has(static::RESOURCE_VERSION_QUERY_PARAMETER);
Chris@5 91
Chris@5 92 // If the resource type is not versionable, then nothing needs to be
Chris@5 93 // enhanced.
Chris@5 94 if (!$resource_type->isVersionable()) {
Chris@5 95 // If the query parameter was provided but the resource type is not
Chris@5 96 // versionable, provide a helpful error.
Chris@5 97 if ($has_version_param) {
Chris@5 98 // Until Drupal core has a generic revision access API, it is only safe
Chris@5 99 // to support the `node` and `media` entity types because they are the
Chris@5 100 // only // entity types that have revision access checks for forward
Chris@5 101 // revisions that are not the default and not the latest revision.
Chris@5 102 $cacheability = (new CacheableMetadata())->addCacheContexts(['url.path', static::CACHE_CONTEXT]);
Chris@5 103 /* Uncomment the next line and remove the following one when https://www.drupal.org/project/drupal/issues/3002352 lands in core. */
Chris@5 104 /* throw new CacheableHttpException($cacheability, 501, 'Resource versioning is not yet supported for this resource type.'); */
Chris@5 105 $message = 'JSON:API does not yet support resource versioning for this resource type.';
Chris@5 106 $message .= ' For context, see https://www.drupal.org/project/jsonapi/issues/2992833#comment-12818258.';
Chris@5 107 $message .= ' To contribute, see https://www.drupal.org/project/drupal/issues/2350939 and https://www.drupal.org/project/drupal/issues/2809177.';
Chris@5 108 throw new CacheableHttpException($cacheability, 501, $message, NULL, []);
Chris@5 109 }
Chris@5 110 return $defaults;
Chris@5 111 }
Chris@5 112
Chris@5 113 // Since the resource type is versionable, responses must always vary by the
Chris@5 114 // requested version, without regard for whether a version query parameter
Chris@5 115 // was provided or not.
Chris@5 116 if (isset($defaults['entity'])) {
Chris@5 117 assert($defaults['entity'] instanceof EntityInterface);
Chris@5 118 $defaults['entity']->addCacheContexts([static::CACHE_CONTEXT]);
Chris@5 119 }
Chris@5 120
Chris@5 121 // If no version was specified, nothing is left to enhance.
Chris@5 122 if (!$has_version_param) {
Chris@5 123 return $defaults;
Chris@5 124 }
Chris@5 125
Chris@5 126 // Provide a helpful error when a version is specified with an unsafe
Chris@5 127 // method.
Chris@5 128 if (!$request->isMethodCacheable()) {
Chris@5 129 throw new BadRequestHttpException(sprintf('%s requests with a `%s` query parameter are not supported.', $request->getMethod(), static::RESOURCE_VERSION_QUERY_PARAMETER));
Chris@5 130 }
Chris@5 131
Chris@5 132 $resource_version_identifier = $request->query->get(static::RESOURCE_VERSION_QUERY_PARAMETER);
Chris@5 133
Chris@5 134 if (!static::isValidVersionIdentifier($resource_version_identifier)) {
Chris@5 135 $cacheability = (new CacheableMetadata())->addCacheContexts([static::CACHE_CONTEXT]);
Chris@5 136 $message = sprintf('A resource version identifier was provided in an invalid format: `%s`', $resource_version_identifier);
Chris@5 137 throw new CacheableBadRequestHttpException($cacheability, $message);
Chris@5 138 }
Chris@5 139
Chris@5 140 // Determine if the request is for a collection resource.
Chris@5 141 if ($defaults[RouteObjectInterface::CONTROLLER_NAME] === Routes::CONTROLLER_SERVICE_NAME . ':getCollection') {
Chris@5 142 $latest_version_identifier = 'rel' . VersionNegotiator::SEPARATOR . 'latest-version';
Chris@5 143 $working_copy_identifier = 'rel' . VersionNegotiator::SEPARATOR . 'working-copy';
Chris@5 144 // Until Drupal core has a revision access API that works on entity
Chris@5 145 // queries, filtering is not permitted on non-default revisions.
Chris@5 146 if ($request->query->has('filter') && $resource_version_identifier !== $latest_version_identifier) {
Chris@5 147 $cache_contexts = [
Chris@5 148 'url.path',
Chris@5 149 static::CACHE_CONTEXT,
Chris@5 150 'url.query_args:filter',
Chris@5 151 ];
Chris@5 152 $cacheability = (new CacheableMetadata())->addCacheContexts($cache_contexts);
Chris@5 153 $message = 'JSON:API does not support filtering on revisions other than the latest version because a secure Drupal core API does not yet exist to do so.';
Chris@5 154 throw new CacheableHttpException($cacheability, 501, $message, NULL, []);
Chris@5 155 }
Chris@5 156 // 'latest-version' and 'working-copy' are the only acceptable version
Chris@5 157 // identifiers for a collection resource.
Chris@5 158 if (!in_array($resource_version_identifier, [$latest_version_identifier, $working_copy_identifier])) {
Chris@5 159 $cacheability = (new CacheableMetadata())->addCacheContexts(['url.path', static::CACHE_CONTEXT]);
Chris@5 160 $message = sprintf('Collection resources only support the following resource version identifiers: %s', implode(', ', [
Chris@5 161 $latest_version_identifier,
Chris@5 162 $working_copy_identifier,
Chris@5 163 ]));
Chris@5 164 throw new CacheableBadRequestHttpException($cacheability, $message);
Chris@5 165 }
Chris@5 166 // Whether the collection to be loaded should include only working copies.
Chris@5 167 $defaults[static::WORKING_COPIES_REQUESTED] = $resource_version_identifier === $working_copy_identifier;
Chris@5 168 return $defaults;
Chris@5 169 }
Chris@5 170
Chris@5 171 /** @var \Drupal\Core\Entity\EntityInterface $entity */
Chris@5 172 $entity = $defaults['entity'];
Chris@5 173
Chris@5 174 /** @var \Drupal\jsonapi\Revisions\VersionNegotiatorInterface $negotiator */
Chris@5 175 $resolved_revision = $this->versionNegotiator->getRevision($entity, $resource_version_identifier);
Chris@5 176 // Ensure none of the original entity cacheability is lost, especially the
Chris@5 177 // query argument's cache context.
Chris@5 178 $resolved_revision->addCacheableDependency($entity);
Chris@5 179 return ['entity' => $resolved_revision] + $defaults;
Chris@5 180 }
Chris@5 181
Chris@5 182 /**
Chris@5 183 * Validates the user input.
Chris@5 184 *
Chris@5 185 * @param string $resource_version
Chris@5 186 * The requested resource version identifier.
Chris@5 187 *
Chris@5 188 * @return bool
Chris@5 189 * TRUE if the received resource version value is valid, FALSE otherwise.
Chris@5 190 */
Chris@5 191 protected static function isValidVersionIdentifier($resource_version) {
Chris@5 192 return preg_match(static::VERSION_IDENTIFIER_VALIDATOR, $resource_version) === 1;
Chris@5 193 }
Chris@5 194
Chris@5 195 }