You are here

public function JsonApiSchemaController::getDocumentSchema in JSON:API Schema 8

File

src/Controller/JsonApiSchemaController.php, line 122

Class

JsonApiSchemaController

Namespace

Drupal\jsonapi_schema\Controller

Code

public function getDocumentSchema(Request $request, $resource_type, $route_type) {
  if (is_array($resource_type)) {
    $titles = array_map(function (ResourceType $type) use ($route_type) {
      return $this
        ->getSchemaTitle($this->resourceTypeRepository
        ->getByTypeName($type), $route_type);
    }, $resource_type);
    $title = count($titles) === 2 ? implode(' and ', $titles) : implode(', ', array_slice($titles, -1)) . ', and ' . end($titles);
  }
  else {
    $title = $this
      ->getSchemaTitle($this->resourceTypeRepository
      ->getByTypeName($resource_type), $route_type);
  }
  $schema = [
    '$schema' => static::JSON_SCHEMA_DRAFT,
    '$id' => $request
      ->getUri(),
    'title' => $title,
    'allOf' => [
      [
        '$ref' => static::JSONAPI_BASE_SCHEMA_URI,
      ],
      [
        'if' => [
          '$ref' => static::JSONAPI_BASE_SCHEMA_URI . '#/definitions/success',
        ],
        'then' => [
          'type' => 'object',
          'properties' => [
            'data' => [
              '$ref' => '#/definitions/data',
            ],
          ],
          'required' => [
            'data',
          ],
        ],
      ],
    ],
  ];
  $cacheability = new CacheableMetadata();
  $get_schema_ref = function ($resource_type) use ($cacheability) {
    $schema_url = Url::fromRoute("jsonapi_schema.{$resource_type}.type")
      ->setAbsolute()
      ->toString(TRUE);
    $cacheability
      ->addCacheableDependency($schema_url);
    return [
      '$ref' => $schema_url
        ->getGeneratedUrl(),
    ];
  };
  $type_schema = is_array($resource_type) ? [
    'anyOf' => array_map($get_schema_ref, $resource_type),
  ] : $get_schema_ref($resource_type);
  switch ($route_type) {
    case 'item':
      $schema['definitions']['data'] = $type_schema;
      break;
    case 'collection':
      $schema['definitions']['data'] = [
        'type' => 'array',
        'items' => $type_schema,
      ];
      break;
    case 'relationship':
      assert('not implemented');
      break;
  }
  return CacheableJsonResponse::create($schema)
    ->addCacheableDependency($cacheability);
}