You are here

public function EntityToJsonApi::serialize in JSON:API Extras 8.3

Same name and namespace in other branches
  1. 8.2 src/EntityToJsonApi.php \Drupal\jsonapi_extras\EntityToJsonApi::serialize()

Return the requested entity as a raw string.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity to generate the JSON from.

string[] $includes: The list of includes.

Return value

string The raw JSON string of the requested resource.

Throws

\Exception

1 call to EntityToJsonApi::serialize()
EntityToJsonApi::normalize in src/EntityToJsonApi.php
Return the requested entity as an structured array.

File

src/EntityToJsonApi.php, line 89

Class

EntityToJsonApi
Simplifies the process of generating a JSON:API version of an entity.

Namespace

Drupal\jsonapi_extras

Code

public function serialize(EntityInterface $entity, array $includes = []) {
  $resource_type = $this->resourceTypeRepository
    ->get($entity
    ->getEntityTypeId(), $entity
    ->bundle());
  $route_name = sprintf('jsonapi.%s.individual', $resource_type
    ->getTypeName());
  $route_options = [];
  if ($resource_type
    ->isVersionable() && $entity instanceof RevisionableInterface && ($revision_id = $entity
    ->getRevisionId())) {
    $route_options['query']['resourceVersion'] = 'id:' . $revision_id;
  }
  $jsonapi_url = Url::fromRoute($route_name, [
    'entity' => $entity
      ->uuid(),
  ], $route_options)
    ->toString(TRUE)
    ->getGeneratedUrl();
  $query = [];
  if ($includes) {
    $query = [
      'include' => implode(',', $includes),
    ];
  }
  $request = Request::create($jsonapi_url, 'GET', $query, $this->currentRequest->cookies
    ->all(), [], $this->currentRequest->server
    ->all());
  if ($this->session) {
    $request
      ->setSession($this->session);
  }
  $response = $this->httpKernel
    ->handle($request, HttpKernelInterface::SUB_REQUEST);
  return $response
    ->getContent();
}