function FieldNormalizer::denormalize

Same name in this branch
  1. 10 core/modules/serialization/src/Normalizer/FieldNormalizer.php \Drupal\serialization\Normalizer\FieldNormalizer::denormalize()
Same name in other branches
  1. 9 core/modules/jsonapi/src/Normalizer/FieldNormalizer.php \Drupal\jsonapi\Normalizer\FieldNormalizer::denormalize()
  2. 9 core/modules/serialization/src/Normalizer/FieldNormalizer.php \Drupal\serialization\Normalizer\FieldNormalizer::denormalize()
  3. 8.9.x core/modules/jsonapi/src/Normalizer/FieldNormalizer.php \Drupal\jsonapi\Normalizer\FieldNormalizer::denormalize()
  4. 8.9.x core/modules/serialization/src/Normalizer/FieldNormalizer.php \Drupal\serialization\Normalizer\FieldNormalizer::denormalize()
  5. 11.x core/modules/jsonapi/src/Normalizer/FieldNormalizer.php \Drupal\jsonapi\Normalizer\FieldNormalizer::denormalize()
  6. 11.x core/modules/serialization/src/Normalizer/FieldNormalizer.php \Drupal\serialization\Normalizer\FieldNormalizer::denormalize()

File

core/modules/jsonapi/src/Normalizer/FieldNormalizer.php, line 38

Class

FieldNormalizer
Converts the Drupal field structure to a JSON:API array structure.

Namespace

Drupal\jsonapi\Normalizer

Code

public function denormalize($data, $class, $format = NULL, array $context = []) : mixed {
    $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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.