ResourceObjectNormalizer.php in JSON:API 8.2
File
src/Normalizer/ResourceObjectNormalizer.php
View source
<?php
namespace Drupal\jsonapi\Normalizer;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\Normalizer\Value\CacheableNormalization;
use Drupal\jsonapi\Normalizer\Value\CacheableOmission;
class ResourceObjectNormalizer extends NormalizerBase {
protected $supportedInterfaceOrClass = ResourceObject::class;
public function supportsDenormalization($data, $type, $format = NULL) {
return FALSE;
}
public function normalize($object, $format = NULL, array $context = []) {
assert($object instanceof ResourceObject);
$context['resource_object'] = $object;
$resource_type = $object
->getResourceType();
$resource_type_name = $resource_type
->getTypeName();
$fields = $object
->getFields();
if (!empty($context['sparse_fieldset'][$resource_type_name])) {
$field_names = $context['sparse_fieldset'][$resource_type_name];
}
else {
$field_names = array_keys($fields);
}
$normalizer_values = [];
foreach ($fields as $field_name => $field) {
$in_sparse_fieldset = in_array($field_name, $field_names);
if (!$in_sparse_fieldset) {
continue;
}
$normalizer_values[$field_name] = $this
->serializeField($field, $context, $format);
}
$relationship_field_names = array_keys($resource_type
->getRelatableResourceTypes());
return CacheableNormalization::aggregate([
'type' => CacheableNormalization::permanent($resource_type
->getTypeName()),
'id' => CacheableNormalization::permanent($object
->getId()),
'attributes' => CacheableNormalization::aggregate(array_diff_key($normalizer_values, array_flip($relationship_field_names)))
->omitIfEmpty(),
'relationships' => CacheableNormalization::aggregate(array_intersect_key($normalizer_values, array_flip($relationship_field_names)))
->omitIfEmpty(),
'links' => $this->serializer
->normalize($object
->getLinks(), $format, $context)
->omitIfEmpty(),
])
->withCacheableDependency($object);
}
protected function serializeField($field, array $context, $format) {
if ($field instanceof FieldItemListInterface) {
$field_access_result = $field
->access('view', $context['account'], TRUE);
if (!$field_access_result
->isAllowed()) {
return new CacheableOmission(CacheableMetadata::createFromObject($field_access_result));
}
$normalized_field = $this->serializer
->normalize($field, $format, $context);
assert($normalized_field instanceof CacheableNormalization);
return $normalized_field
->withCacheableDependency(CacheableMetadata::createFromObject($field_access_result));
}
else {
return CacheableNormalization::permanent($field);
}
}
}