-
-
Notifications
You must be signed in to change notification settings - Fork 969
Description
API Platform version(s) affected: v2.5.6
Description
On a Collection Get resource with Pagination plugin, when the collection is empty, the expected body should be an empty array. Both json & ld+json was working before 5.1.x
On this version of Symfony, now it will no more normalize the Paginator, but will just return the object and the response will be an empty object like this "{}" instead of the empty array like this "[]"
The problem comes from the Symfony\Component\Serializer\Serializer::normalize.
Before 5.1.0 it does this:
if (\is_array($data) || $data instanceof \Traversable) {
$normalized = [];
foreach ($data as $key => $val) {
$normalized[$key] = $this->normalize($val, $format, $context);
}
return $normalized;
}
Since Symfony 5.1.0 it also adds a check on data lenght like this:
if (\is_array($data) || $data instanceof \Traversable) {
if ($data instanceof \Countable && 0 === $data->count()) {
return $data;
}
$normalized = [];
foreach ($data as $key => $val) {
$normalized[$key] = $this->normalize($val, $format, $context);
}
return $normalized;
}
How to reproduce
With a simple DataProvider that implements CollectionDataProviderInterface and which query returns nothing (add a where 1 = 0) :
public function getCollection(string $resourceClass, string $operationName = null, array $context = [])
{
$repository = $this->managerRegistry->getRepository(AnyEntity::class);
$queryBuilder = $prescripterRepository->createQueryBuilder('pre');
$queryBuilder->where("1 = 0");
$data = null;
foreach ($this->collectionExtensions as $extension) {
$extension->applyToCollection($queryBuilder, new QueryNameGenerator(), $resourceClass, $operationName, $context);
if ($extension instanceof QueryResultCollectionExtensionInterface
&& $extension->supportsResult($resourceClass, $operationName)
) {
$data = $extension->getResult($queryBuilder);
}
}
if (!$data) {
$data = $queryBuilder->getQuery()->getResult();
}
return $data;
}
Possible Solution
No solution for instance
Additional Context
Json response before 5.1 : []
Json response after 5.1 : {}