FieldNormalizer.php in Drupal 9
File
core/modules/jsonapi/src/Normalizer/FieldNormalizer.php
View source
<?php
namespace Drupal\jsonapi\Normalizer;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\Normalizer\Value\CacheableNormalization;
use Drupal\jsonapi\ResourceType\ResourceType;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class FieldNormalizer extends NormalizerBase implements DenormalizerInterface {
protected $supportedInterfaceOrClass = FieldItemListInterface::class;
public function normalize($field, $format = NULL, array $context = []) {
$normalized_items = $this
->normalizeFieldItems($field, $format, $context);
assert($context['resource_object'] instanceof ResourceObject);
return $context['resource_object']
->getResourceType()
->getFieldByInternalName($field
->getName())
->hasOne() ? array_shift($normalized_items) ?: CacheableNormalization::permanent(NULL) : CacheableNormalization::aggregate($normalized_items);
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
$field_definition = $context['field_definition'];
assert($field_definition instanceof FieldDefinitionInterface);
$resource_type = $context['resource_type'];
assert($resource_type instanceof ResourceType);
$is_already_itemized = is_array($data) && array_reduce(array_keys($data), function ($carry, $index) {
return $carry && is_numeric($index);
}, TRUE);
$itemized_data = $is_already_itemized ? $data : [
0 => $data,
];
$field_item_class = $field_definition
->getItemDefinition()
->getClass();
if (count($itemized_data) === 1 && $resource_type
->getFieldByInternalName($field_definition
->getName())
->hasOne()) {
return $this->serializer
->denormalize($itemized_data[0], $field_item_class, $format, $context);
}
$data_internal = [];
foreach ($itemized_data as $delta => $field_item_value) {
$data_internal[$delta] = $this->serializer
->denormalize($field_item_value, $field_item_class, $format, $context);
}
return $data_internal;
}
protected function normalizeFieldItems(FieldItemListInterface $field, $format, array $context) {
$normalizer_items = [];
if (!$field
->isEmpty()) {
foreach ($field as $field_item) {
$normalizer_items[] = $this->serializer
->normalize($field_item, $format, $context);
}
}
return $normalizer_items;
}
}
Classes
Name |
Description |
FieldNormalizer |
Converts the Drupal field structure to a JSON:API array structure. |