PHP code example of opwoco / query-filter-bundle

1. Go to this page and download the library: Download opwoco/query-filter-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

opwoco / query-filter-bundle example snippets




namespace App\Controller;

use Artprima\QueryFilterBundle\QueryFilter\Config\BaseConfig; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Artprima\QueryFilterBundle\Request\Request;
use Artprima\QueryFilterBundle\QueryFilter\QueryFilter;
use Artprima\QueryFilterBundle\Response\Response;
use App\Repository\ItemRepository;

class DefaultController extends Controller
{
    // ...
    
    /**
     * @Route("/") 
     */
    public function indexAction(HttpRequest $request, ItemRepository $repository)
    {
        // set up the config
        $config = new BaseConfig();
        $config->setSearchAllowedCols(['t.name']);
        $config->setAllowedLimits([10, 25, 50, 100]);
        $config->setDefaultLimit(10);
        $config->setSortCols(['t.id'], ['t.id' => 'asc']);
        $config->setRequest(new Request($request));
        
        // here we provide a repository callback that will be used internally in the QueryFilter
        // The signature of the method must be as follows: function functionName(QueryFilterArgs $args): QueryResult;
        $config->setRepositoryCallback([$repository, 'findByOrderBy']);
        
        // Response must implement Artprima\QueryFilterBundle\Response\ResponseInterface
        $queryFilter = new QueryFilter(Response::class);
        /** @var Response $data the type of the variable is defined by the class in the first argument of QueryFilter's constructor */
        $response = $queryFilter->getData($config);
        $data = $response->getData();
        $meta = $response->getMeta();
        
        // ... now do something with $data or $meta
    }
    
    // ...
}



namespace App\Repository;

use App\Entity\Item;
use Artprima\QueryFilterBundle\Query\Mysql\PaginationWalker;
use Artprima\QueryFilterBundle\Query\ConditionManager;
use Artprima\QueryFilterBundle\Query\ProxyQueryBuilder;
use Artprima\QueryFilterBundle\QueryFilter\QueryFilterArgs;
use Artprima\QueryFilterBundle\QueryFilter\QueryResult;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

class ItemRepository extends ServiceEntityRepository
{
    /**
     * @var ConditionManager
     */
    private $pqbManager;

    public function __construct(RegistryInterface $registry, ConditionManager $manager)
    {
        parent::__construct($registry, Item::class);
        $this->pqbManager = $manager;
    }

    
    public function findByOrderBy(QueryFilterArgs $args): QueryResult
    {
        // Build our request
        $qb = $this->createQueryBuilder('t')
            ->setFirstResult($args->getOffset())
            ->setMaxResults($args->getLimit());

        $proxyQb = new ProxyQueryBuilder($qb, $this->pqbManager);
        $qb = $proxyQb->getSortedAndFilteredQueryBuilder($args->getSearchBy(), $args->getSortBy());
        $query = $qb->getQuery();
        $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, PaginationWalker::class);
        $query->setHint("mysqlWalker.sqlCalcFoundRows", true);
        $result = $query->getResult();
        $totalRows = $this->_em->getConnection()->query('SELECT FOUND_ROWS()')->fetchColumn();
        
        // return the wrapped result
        return new QueryResult($result, $totalRows);
    }    
    
    // ...
}



return [
    // ...
    Artprima\QueryFilterBundle\ArtprimaQueryFilterBundle::class => ['all' => true],
    FOS\RestBundle\FOSRestBundle::class => ['all' => true],
    JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
    // ...
];



namespace App\Controller;

use App\QueryFilter\Response;
use App\Repository\ItemRepository;
use Artprima\QueryFilterBundle\QueryFilter\Config\ConfigInterface as QueryFilterConfigInterface;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Artprima\QueryFilterBundle\Controller\Annotations\QueryFilter;

class ItemController extends FOSRestController implements ClassResourceInterface
{
    /**
     * @Rest\View(serializerEnableMaxDepthChecks=true)
     * @ParamConverter("config", class="App\QueryFilter\Config\ItemConfig",
     *                           converter="query_filter_config_converter",
     *                           options={"entity_class": "App\Entity\Item", "repository_method": "findByOrderBy"})
     * @QueryFilter()
     * @Rest\Get("/items")
     */
    public function cgetAction(QueryFilterConfigInterface $config)
    {
        return $config;
    }
}



namespace App\Repository;

use App\Entity\Item;
use Artprima\QueryFilterBundle\Query\Mysql\PaginationWalker;
use Artprima\QueryFilterBundle\Query\ConditionManager;
use Artprima\QueryFilterBundle\Query\ProxyQueryBuilder;
use Artprima\QueryFilterBundle\QueryFilter\QueryFilterArgs;
use Artprima\QueryFilterBundle\QueryFilter\QueryResult;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method Item|null find($id, $lockMode = null, $lockVersion = null)
 * @method Item|null findOneBy(array $criteria, array $orderBy = null)
 * @method Item[]    findAll()
 * @method Item[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class ItemRepository extends ServiceEntityRepository
{
    /**
     * @var ConditionManager
     */
    private $pqbManager;

    public function __construct(RegistryInterface $registry, ConditionManager $manager)
    {
        parent::__construct($registry, Item::class);
        $this->pqbManager = $manager;
    }

    public function findByOrderBy(QueryFilterArgs $args): QueryResult
    {
        $qb = $this->createQueryBuilder('t')
            ->setFirstResult($args->getOffset())
            ->setMaxResults($args->getLimit());

        $proxyQb = new ProxyQueryBuilder($qb, $this->pqbManager);
        $qb = $proxyQb->getSortedAndFilteredQueryBuilder($args->getSearchBy(), $args->getSortBy());
        $query = $qb->getQuery();
        $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, PaginationWalker::class);
        $query->setHint("mysqlWalker.sqlCalcFoundRows", true);
        $result = $query->getResult();
        $totalRows = $this->_em->getConnection()->query('SELECT FOUND_ROWS()')->fetchColumn();

        return new QueryResult($result, $totalRows);
    }
}



namespace App\QueryFilter\Config;

use Artprima\QueryFilterBundle\QueryFilter\Config\BaseConfig;

class ItemConfig extends BaseConfig
{
    public function __construct()
    {
        $this->setSearchAllowedCols(array(
            't.name',
        ));

        $this->setSortCols(
            array(
                't.id',
            ),
            array('t.id' => 'desc') // default
        );
    }
}