diff --git a/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php b/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php index 32f2a94..9d5cf89 100644 --- a/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php +++ b/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php @@ -184,7 +184,9 @@ class JsonApiDocumentTopLevelNormalizer extends NormalizerBase implements Denorm return $serializer->normalize($entity, $format, $context); }, $entities); - return new JsonApiDocumentTopLevelNormalizerValue($normalizer_values, $object->getLinks(), $is_collection); + $total_count = $is_collection && $context['resource_type']->includeCount() ? $data->getTotalCount() : FALSE; + + return new JsonApiDocumentTopLevelNormalizerValue($normalizer_values, $object->getLinks(), $is_collection, $total_count); } /** diff --git a/src/Normalizer/Value/JsonApiDocumentTopLevelNormalizerValue.php b/src/Normalizer/Value/JsonApiDocumentTopLevelNormalizerValue.php index 544f580..3bfdc4b 100644 --- a/src/Normalizer/Value/JsonApiDocumentTopLevelNormalizerValue.php +++ b/src/Normalizer/Value/JsonApiDocumentTopLevelNormalizerValue.php @@ -46,6 +46,11 @@ class JsonApiDocumentTopLevelNormalizerValue implements ValueExtractorInterface, */ protected $isCollection; + /** + * @var int + */ + protected $totalCount; + /** * Instantiates a JsonApiDocumentTopLevelNormalizerValue object. * @@ -56,8 +61,12 @@ class JsonApiDocumentTopLevelNormalizerValue implements ValueExtractorInterface, * The URLs to which to link. * @param bool $is_collection * TRUE if this is a serialization for a list. + * @param int $total_count + * (optional) A total count of resources available in a collection without + * respect for access control. */ - public function __construct(array $values, array $links, $is_collection = FALSE) { + public function __construct(array $values, array $links, $is_collection = FALSE, $total_count = FALSE) { + assert($total_count === FALSE || $is_collection, 'Only collection documents can contain result counts.'); $this->values = $values; array_walk($values, [$this, 'addCacheableDependency']); // Make sure that different sparse fieldsets are cached differently. @@ -93,6 +102,7 @@ class JsonApiDocumentTopLevelNormalizerValue implements ValueExtractorInterface, }, []); // Filter the empty values. $this->includes = array_filter($this->includes); + $this->totalCount = $total_count; } /** @@ -111,6 +121,10 @@ class JsonApiDocumentTopLevelNormalizerValue implements ValueExtractorInterface, 'links' => $this->links, ]; + if ($this->totalCount !== FALSE) { + $rasterized['meta']['count'] = $this->totalCount; + } + foreach ($this->values as $normalizer_value) { if ($normalizer_value instanceof HttpExceptionNormalizerValue) { $previous_errors = NestedArray::getValue($rasterized, ['meta', 'errors']) ?: [];