jsonapi.services.yml | 2 +- src/EntityToJsonApi.php | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/jsonapi.services.yml b/jsonapi.services.yml index 0dc5f88..0fd7814 100644 --- a/jsonapi.services.yml +++ b/jsonapi.services.yml @@ -131,7 +131,7 @@ services: jsonapi.entity.to_jsonapi: class: Drupal\jsonapi\EntityToJsonApi - arguments: ['@http_kernel'] + arguments: ['@http_kernel', '@request_stack'] logger.channel.jsonapi: parent: logger.channel_base diff --git a/src/EntityToJsonApi.php b/src/EntityToJsonApi.php index f54fbab..6bed824 100644 --- a/src/EntityToJsonApi.php +++ b/src/EntityToJsonApi.php @@ -5,6 +5,7 @@ namespace Drupal\jsonapi; use Drupal\Component\Serialization\Json; use Drupal\Core\Entity\EntityInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\HttpKernelInterface; /** @@ -22,13 +23,21 @@ class EntityToJsonApi { protected $httpKernel; /** + * The request stack. + * + * @var \Symfony\Component\HttpFoundation\RequestStack + */ + protected $requestStack; + + /** * EntityToJsonApi constructor. * * @param \Symfony\Component\HttpKernel\HttpKernelInterface * The HTTP kernel. */ - public function __construct(HttpKernelInterface $http_kernel) { + public function __construct(HttpKernelInterface $http_kernel, RequestStack $request_stack) { $this->httpKernel = $http_kernel; + $this->requestStack = $request_stack; } /** @@ -41,8 +50,9 @@ class EntityToJsonApi { * The raw JSON string of the requested resource. */ public function serialize(EntityInterface $entity) { - $path = sprintf('/jsonapi/%s/%s/%s', $entity->getEntityTypeId(), $entity->bundle(), $entity->uuid()); - $request = Request::create($path, 'GET', ['_format' => 'api_json']); + $master_request = $this->requestStack->getMasterRequest(); + $path = sprintf('%s/jsonapi/%s/%s/%s', $master_request->getBasePath(), $entity->getEntityTypeId(), $entity->bundle(), $entity->uuid()); + $request = Request::create($path, 'GET', ['_format' => 'api_json'], $master_request->cookies->all(), [], $master_request->server->all()); $response = $this->httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST, TRUE); return $response->getContent(); }