You are here

public function Controller::serialize in Schemata 8

Serializes a entity type or bundle definition.

We have 2 different data formats involved. One is the schema format (for instance JSON Schema) and the other one is the format that the schema is describing (for instance jsonapi, json, hal+json, …). We need to provide both formats. Something like: ?_format=schema_json&_describes=api_json.

Parameters

string $entity_type_id: The entity type ID to describe.

string $bundle: The (optional) bundle to describe.

\Symfony\Component\HttpFoundation\Request $request: The request object.

Return value

\Drupal\Core\Cache\CacheableResponse The response object.

File

src/Controller/Controller.php, line 85

Class

Controller
Contains callback methods for dynamic routes.

Namespace

Drupal\schemata\Controller

Code

public function serialize($entity_type_id, Request $request, $bundle = NULL) {
  $parts = $this
    ->extractFormatNames($request);

  // Load the data to serialize from the route information on the current
  // request.
  $schema = $this->schemaFactory
    ->create($entity_type_id, $bundle);

  // Serialize the entity type/bundle definition.
  $format = implode(':', $parts);
  $content = $this->serializer
    ->serialize($schema, $format);

  // Finally, set the contents of the response and return it.
  $this->response
    ->addCacheableDependency($schema);
  $cacheable_dependency = (new CacheableMetadata())
    ->addCacheContexts([
    'url.query_args:_describes',
  ]);
  $this->response
    ->addCacheableDependency($cacheable_dependency);
  $this->response
    ->setContent($content);
  $this->response->headers
    ->set('Content-Type', $request
    ->getMimeType($parts[0]));
  return $this->response;
}