function FieldItemNormalizer::getNormalizationSchema

Overrides SchematicNormalizerTrait::getNormalizationSchema

File

core/modules/jsonapi/src/Normalizer/FieldItemNormalizer.php, line 243

Class

FieldItemNormalizer
Converts the Drupal field item object to a JSON:API array structure.

Namespace

Drupal\jsonapi\Normalizer

Code

protected function getNormalizationSchema(mixed $object, array $context = []) : array {
    $schema = [
        'type' => 'object',
    ];
    if (is_string($object)) {
        return [
            '$comment' => 'No detailed schema available.',
        ] + $schema;
    }
    assert($object instanceof FieldItemInterface);
    $field_properties = TypedDataInternalPropertiesHelper::getNonInternalProperties($object);
    if (count($field_properties) === 0) {
        // The field item has only internal (or no) properties. In this case, the
        // value is normalized from ::getValue(). Use a schema from the method or
        // interface, if available.
        return $this->getJsonSchemaForMethod($object, 'getValue', [
            '$comment' => sprintf('Cannot determine schema for %s::getValue().', $object::class),
        ]);
    }
    // If we did not early return, iterate over the non-internal properties.
    foreach ($field_properties as $property_name => $property) {
        $property_schema = [
            'title' => (string) $property->getDataDefinition()
                ->getLabel(),
        ];
        assert($this->serializer instanceof JsonSchemaProviderSerializerInterface);
        $property_schema = array_merge($this->serializer
            ->getJsonSchema($property, $context), $property_schema);
        $schema['properties'][$property_name] = $property_schema;
    }
    // Flatten if there is only a single property to normalize.
    if (count($field_properties) === 1 && $object::mainPropertyName() !== NULL) {
        $schema = $schema['properties'][$object::mainPropertyName()] ?? [];
    }
    return $schema;
}

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