EntityToJsonApi.php in JSON:API Extras 8.3
File
src/EntityToJsonApi.php
View source
<?php
namespace Drupal\jsonapi_extras;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class EntityToJsonApi {
protected $httpKernel;
protected $resourceTypeRepository;
protected $session;
protected $currentRequest;
public function __construct(HttpKernelInterface $http_kernel, ResourceTypeRepositoryInterface $resource_type_repository, SessionInterface $session, RequestStack $request_stack) {
$this->httpKernel = $http_kernel;
$this->resourceTypeRepository = $resource_type_repository;
$this->currentRequest = $request_stack
->getCurrentRequest();
$this->session = $this->currentRequest
->hasPreviousSession() ? $this->currentRequest
->getSession() : $session;
}
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();
}
public function normalize(EntityInterface $entity, array $includes = []) {
return Json::decode($this
->serialize($entity, $includes));
}
}
Classes
Name |
Description |
EntityToJsonApi |
Simplifies the process of generating a JSON:API version of an entity. |