ItsJohnB ItsJohnB - 6 months ago 13
PHP Question

Symfony 2.8 SyliusRecourceBundle routing criteria

Right now I have a strange issue. Recently I started developing in Symfony 2.8. To learn in this framework I made an own project with an API. Everything works until i face a Route with a Criteria.

According to the documentation I only need to add "criteria" in the route file. But it isn't showing any difference. But when I add a "limit" too. Then it is working.

The Route file (A and B are fake):

api_A_B:
path: /A/{id}/B
methods: [GET]
defaults:
_controller: api.controller.B:indexAction
_sylius:
paginate: false
#limit: 900 #WHY?
criteria:
A: $id


I read something about "filterable: true" but that was ages ago and it isn't in the documentation.

Query response with limit:

FROM
B t0
WHERE
t0.A_id = ?
LIMIT
900


Query response without limit:

FROM
B t0

Answer

This is a bug in the default Sylius resource resolver, it ignores criteria and sorting when your not paginating or limit is unset. To solve this, you should override the sylius.resource_controller.resources_resolver.class parameter and use the following implementation for the getResources method:

public function getResources(RequestConfiguration $requestConfiguration, RepositoryInterface $repository)
{
    if (null !== $repositoryMethod = $requestConfiguration->getRepositoryMethod()) {
        $callable = [$repository, $repositoryMethod];
        $resources = call_user_func_array($callable, $requestConfiguration->getRepositoryArguments());

        return $resources;
    }

    // this has changed!
    if (!$requestConfiguration->isPaginated() && !$requestConfiguration->isLimited()) {
        return $repository->findBy($requestConfiguration->getCriteria(), $requestConfiguration->getSorting(), $requestConfiguration->getLimit());
    }

    if (!$requestConfiguration->isPaginated()) {
        return $repository->findBy($requestConfiguration->getCriteria(), $requestConfiguration->getSorting(), $requestConfiguration->getLimit());
    }

    return $repository->createPaginator($requestConfiguration->getCriteria(), $requestConfiguration->getSorting());
}
Comments