You are here

protected function JsonApiSchemaController::addFieldsSchema in JSON:API Schema 8

1 call to JsonApiSchemaController::addFieldsSchema()
JsonApiSchemaController::getResourceObjectSchema in src/Controller/JsonApiSchemaController.php

File

src/Controller/JsonApiSchemaController.php, line 211

Class

JsonApiSchemaController

Namespace

Drupal\jsonapi_schema\Controller

Code

protected function addFieldsSchema(array $schema, ResourceType $resource_type) {

  // Filter out disabled fields.
  $resource_fields = array_filter($resource_type
    ->getFields(), function (ResourceTypeField $field) {
    return $field
      ->isFieldEnabled();
  });
  if (empty($resource_fields)) {
    return $schema;
  }
  $schema['allOf'][0]['properties']['attributes'] = [
    '$ref' => '#/definitions/attributes',
  ];
  $normalizer = $this->normalizer;
  $entity_type = $this->entityTypeManager
    ->getDefinition($resource_type
    ->getEntityTypeId());
  $bundle = $resource_type
    ->getBundle();
  $fields = array_reduce($resource_fields, function ($carry, ResourceTypeField $field) use ($normalizer, $entity_type, $bundle) {
    $field_schema = $normalizer
      ->normalize($this->staticDataDefinitionExtractor
      ->extractField($entity_type, $bundle, $field
      ->getInternalName()), 'schema_json', [
      'name' => $field
        ->getPublicName(),
    ]);
    $fields_member = $field instanceof ResourceTypeAttribute ? 'attributes' : 'relationships';
    return NestedArray::mergeDeep($carry, [
      'type' => 'object',
      'properties' => [
        $fields_member => $field_schema,
      ],
    ]);
  }, []);
  $field_definitions = NestedArray::getValue($fields, [
    'properties',
  ]) ?: [];
  if (!empty($field_definitions['attributes'])) {
    $field_definitions['attributes']['additionalProperties'] = FALSE;
  }
  if (!empty($field_definitions['relationships'])) {
    $field_definitions['relationships']['additionalProperties'] = FALSE;
  }
  $schema['definitions'] = NestedArray::mergeDeep($schema['definitions'], $field_definitions);
  return $schema;
}