View source
<?php
namespace Drupal\jsonapi\Normalizer;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Uuid\Uuid;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\jsonapi\JsonApiResource\ErrorCollection;
use Drupal\jsonapi\JsonApiResource\OmittedData;
use Drupal\jsonapi\JsonApiSpec;
use Drupal\jsonapi\Normalizer\Value\CacheableOmission;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\Normalizer\Value\CacheableNormalization;
use Drupal\jsonapi\ResourceType\ResourceType;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
class JsonApiDocumentTopLevelNormalizer extends NormalizerBase implements DenormalizerInterface, NormalizerInterface {
protected $supportedInterfaceOrClass = JsonApiDocumentTopLevel::class;
protected $entityTypeManager;
protected $resourceTypeRepository;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ResourceTypeRepositoryInterface $resource_type_repository) {
$this->entityTypeManager = $entity_type_manager;
$this->resourceTypeRepository = $resource_type_repository;
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
$resource_type = $context['resource_type'];
static::validateRequestBody($data, $resource_type);
$normalized = [];
if (!empty($data['data']['attributes'])) {
$normalized = $data['data']['attributes'];
}
if (!empty($data['data']['id'])) {
$uuid_key = $this->entityTypeManager
->getDefinition($resource_type
->getEntityTypeId())
->getKey('uuid');
$normalized[$uuid_key] = $data['data']['id'];
}
if (!empty($data['data']['relationships'])) {
$relationships = array_map(function ($relationship) {
if (isset($relationship['data']['type']) && isset($relationship['data']['id'])) {
return [
'data' => [
$relationship['data'],
],
];
}
else {
return $relationship;
}
}, $data['data']['relationships']);
$relationships = array_map(function ($relationship) {
if (empty($relationship['data'])) {
return [];
}
if (empty($relationship['data'][0]['id'])) {
throw new BadRequestHttpException("No ID specified for related resource");
}
$id_list = array_column($relationship['data'], 'id');
if (empty($relationship['data'][0]['type'])) {
throw new BadRequestHttpException("No type specified for related resource");
}
if (!($resource_type = $this->resourceTypeRepository
->getByTypeName($relationship['data'][0]['type']))) {
throw new BadRequestHttpException("Invalid type specified for related resource: '" . $relationship['data'][0]['type'] . "'");
}
$entity_type_id = $resource_type
->getEntityTypeId();
try {
$entity_storage = $this->entityTypeManager
->getStorage($entity_type_id);
} catch (PluginNotFoundException $e) {
throw new BadRequestHttpException("Invalid type specified for related resource: '" . $relationship['data'][0]['type'] . "'");
}
$uuid_key = $this->entityTypeManager
->getDefinition($entity_type_id)
->getKey('uuid');
$related_entities = array_values($entity_storage
->loadByProperties([
$uuid_key => $id_list,
]));
$map = [];
foreach ($related_entities as $related_entity) {
$map[$related_entity
->uuid()] = $related_entity
->id();
}
$canonical_ids = [];
foreach ($id_list as $delta => $uuid) {
if (!isset($map[$uuid])) {
if ($uuid === 'virtual') {
continue;
}
throw new NotFoundHttpException(sprintf('The resource identified by `%s:%s` (given as a relationship item) could not be found.', $relationship['data'][$delta]['type'], $uuid));
}
$reference_item = [
'target_id' => $map[$uuid],
];
if (isset($relationship['data'][$delta]['meta'])) {
$reference_item += $relationship['data'][$delta]['meta'];
}
$canonical_ids[] = array_filter($reference_item, function ($key) {
return substr($key, 0, strlen('drupal_internal__')) !== 'drupal_internal__';
}, ARRAY_FILTER_USE_KEY);
}
return array_filter($canonical_ids);
}, $relationships);
$normalized = array_merge($normalized, $relationships);
}
$class = $context['resource_type']
->getDeserializationTargetClass();
return $this->serializer
->denormalize($normalized, $class, $format, $context);
}
public function normalize($object, $format = NULL, array $context = []) {
assert($object instanceof JsonApiDocumentTopLevel);
$data = $object
->getData();
$document['jsonapi'] = CacheableNormalization::permanent([
'version' => JsonApiSpec::SUPPORTED_SPECIFICATION_VERSION,
'meta' => [
'links' => [
'self' => [
'href' => JsonApiSpec::SUPPORTED_SPECIFICATION_PERMALINK,
],
],
],
]);
if ($data instanceof ErrorCollection) {
$document['errors'] = $this
->normalizeErrorDocument($object, $format, $context);
}
else {
$document['data'] = $this->serializer
->normalize($data, $format, $context);
$document['included'] = $this->serializer
->normalize($object
->getIncludes(), $format, $context)
->omitIfEmpty();
$normalized_omissions = $this
->normalizeOmissionsLinks($object
->getOmissions(), $format, $context);
$meta = !$normalized_omissions instanceof CacheableOmission ? array_merge($object
->getMeta(), [
'omitted' => $normalized_omissions
->getNormalization(),
]) : $object
->getMeta();
$document['meta'] = (new CacheableNormalization($normalized_omissions, $meta))
->omitIfEmpty();
}
$document['links'] = $this->serializer
->normalize($object
->getLinks(), $format, $context)
->omitIfEmpty();
return CacheableNormalization::aggregate($document)
->withCacheableDependency((new CacheableMetadata())
->addCacheContexts([
'url.site',
]));
}
protected function normalizeErrorDocument(JsonApiDocumentTopLevel $document, $format, array $context = []) {
$normalized_values = array_map(function (HttpExceptionInterface $exception) use ($format, $context) {
return $this->serializer
->normalize($exception, $format, $context);
}, (array) $document
->getData()
->getIterator());
$cacheability = new CacheableMetadata();
$errors = [];
foreach ($normalized_values as $normalized_error) {
$cacheability
->addCacheableDependency($normalized_error);
$errors = array_merge($errors, $normalized_error
->getNormalization());
}
return new CacheableNormalization($cacheability, $errors);
}
protected function normalizeOmissionsLinks(OmittedData $omissions, $format, array $context = []) {
$normalized_omissions = array_map(function (HttpExceptionInterface $exception) use ($format, $context) {
return $this->serializer
->normalize($exception, $format, $context);
}, $omissions
->toArray());
$cacheability = CacheableMetadata::createFromObject(CacheableNormalization::aggregate($normalized_omissions));
if (empty($normalized_omissions)) {
return new CacheableOmission($cacheability);
}
$omission_links = [
'detail' => 'Some resources have been omitted because of insufficient authorization.',
'links' => [
'help' => [
'href' => 'https://www.drupal.org/docs/8/modules/json-api/filtering#filters-access-control',
],
],
];
$link_hash_salt = Crypt::randomBytesBase64();
foreach ($normalized_omissions as $omission) {
$cacheability
->addCacheableDependency($omission);
foreach ($omission
->getNormalization() as $error) {
$link_key = 'item--' . static::getLinkHash($link_hash_salt, $error['links']['via']['href']);
$omission_links['links'][$link_key] = [
'href' => $error['links']['via']['href'],
'meta' => [
'rel' => 'item',
'detail' => $error['detail'],
],
];
}
}
return new CacheableNormalization($cacheability, $omission_links);
}
protected static function validateRequestBody(array $document, ResourceType $resource_type) {
if (isset($document['relationships']) && !empty($document['relationships'])) {
throw new BadRequestHttpException("Found \"relationships\" within the document's top level. The \"relationships\" key must be within resource object.");
}
if (!isset($document['data']['type'])) {
throw new BadRequestHttpException("Resource object must include a \"type\".");
}
if (isset($document['data']['id']) && !Uuid::isValid($document['data']['id'])) {
throw new UnprocessableEntityHttpException('IDs should be properly generated and formatted UUIDs as described in RFC 4122.');
}
if (isset($document['data']['attributes'])) {
$received_attribute_field_names = array_keys($document['data']['attributes']);
$relationship_field_names = array_keys($resource_type
->getRelatableResourceTypes());
if ($relationship_fields_sent_as_attributes = array_intersect($received_attribute_field_names, $relationship_field_names)) {
throw new UnprocessableEntityHttpException(sprintf("The following relationship fields were provided as attributes: [ %s ]", implode(', ', $relationship_fields_sent_as_attributes)));
}
}
}
protected static function getLinkHash($salt, $link_href) {
return substr(str_replace([
'-',
'_',
], '', Crypt::hashBase64($salt . $link_href)), 0, 7);
}
}