public function FieldNormalizer::denormalize in Drupal 9
Same name in this branch
- 9 core/modules/jsonapi/src/Normalizer/FieldNormalizer.php \Drupal\jsonapi\Normalizer\FieldNormalizer::denormalize()
- 9 core/modules/serialization/src/Normalizer/FieldNormalizer.php \Drupal\serialization\Normalizer\FieldNormalizer::denormalize()
Same name and namespace in other branches
- 8 core/modules/jsonapi/src/Normalizer/FieldNormalizer.php \Drupal\jsonapi\Normalizer\FieldNormalizer::denormalize()
File
- core/
modules/ jsonapi/ src/ Normalizer/ FieldNormalizer.php, line 45
Class
- FieldNormalizer
- Converts the Drupal field structure to a JSON:API array structure.
Namespace
Drupal\jsonapi\NormalizerCode
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);
// If $data contains items (recognizable by numerical array keys, which
// Drupal's Field API calls "deltas"), then it already is itemized; it's not
// using the simplified JSON structure that JSON:API generates.
$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,
];
// Single-cardinality fields don't need itemization.
$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;
}