diff --git a/src/EntityToJsonApi.php b/src/EntityToJsonApi.php index 29ce368..35e534c 100644 --- a/src/EntityToJsonApi.php +++ b/src/EntityToJsonApi.php @@ -49,58 +49,59 @@ class EntityToJsonApi { } /** - * Return the requested entity as a JSON object. + * Return the requested entity as a raw string. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to generate the JSON from. - * @param string $method - * Name of the method to call on the serializer. * - * @return string|array - * The requested resource in JSON form. + * @return string + * The raw JSON string of the requested resource. */ - protected function doAction(EntityInterface $entity, $method) { + public function serialize(EntityInterface $entity) { // TODO: Supporting includes requires adding the 'include' query string. - $request = new Request(); - return call_user_func_array([$this->serializer, $method], [ - new JsonApiDocumentTopLevel($entity), + return $this->serializer->serialize(new JsonApiDocumentTopLevel($entity), 'api_json', - [ - 'account' => $this->currentUser, - 'cacheable_metadata' => new CacheableMetadata(), - 'resource_type' => $this->resourceTypeRepository->get( - $entity->getEntityTypeId(), - $entity->bundle() - ), - 'request' => $request, - ], - ]); + $this->calculateContext($entity) + ); } /** - * Return the requested entity as a raw string. + * Return the requested entity as an structured array. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to generate the JSON from. * - * @return string - * The raw JSON string of the requested resource. + * @return array + * The JSON structure of the requested resource. */ - public function serialize(EntityInterface $entity) { - return $this->doAction($entity, 'serialize'); + public function normalize(EntityInterface $entity) { + return $this->serializer->normalize(new JsonApiDocumentTopLevel($entity), + 'api_json', + $this->calculateContext($entity) + ); } /** - * Return the requested entity as an structured array. + * Calculate the context for the serialize/normalize operation. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to generate the JSON from. * * @return array - * The JSON structure of the requested resource. + * The context. */ - public function normalize(EntityInterface $entity) { - return $this->doAction($entity, 'normalize'); + protected function calculateContext(EntityInterface $entity) { + // TODO: Supporting includes requires adding the 'include' query string. + $request = new Request(); + return [ + 'account' => $this->currentUser, + 'cacheable_metadata' => new CacheableMetadata(), + 'resource_type' => $this->resourceTypeRepository->get( + $entity->getEntityTypeId(), + $entity->bundle() + ), + 'request' => $request, + ]; } }