zoid/doctrine-filter-objects

There is no license information available for the latest version (dev-master) of this package.

dev-master 2019-07-28 20:21 UTC

This package is not auto-updated.

Last update: 2024-05-13 21:39:26 UTC


README

Wrapper around Doctrine\ORM's QueryBuilder. Providing easy-to-use, customizable classes to specify WHERE and ORDER parameters.

Filtering

Create generic filter

$data = [
    'name' => 'David',
    'location' => 'USA',
    'age' => 26,
    'position' => 'IT'
];

$filter = new QueryFilter($data);

// You can specify the relations between parameters
// Untouched parameters will be appended to the end of query with AND operator

$filter ->and('name')
        ->and('location')
            ->or('age', Where::NOT_EQUAL)
            ->end()
        ->and('position', Where::LIKE);
        
// Return DQL Where part with prefixed columns
 
echo $filter->getStatement('c'); 

// "c.name = David AND ((c.location = USA OR c.age <> 26) AND c.position LIKE Manager)"

Use filter in query builder

Since $filter->getStatement() returns string, it's easy to use in Doctrine QueryBuilder.

$qb = $this->em->createQueryBuilder();
$qb ->select('p')
    ->from(Product::class, 'p')
    ->where($filter->getStatement('p');

You can skip passing $prefix parameter by using prepared class FilterApplier

$qb = $this->em->createQueryBuilder();
$qb ->select('p')
    ->from(Product::class, 'p');
    
$applier = new FilterApplier($qb);
$applier->filter($filter);

Create custom filters

You can create custom filter by implementing IQueryFilter interface

class ActiveProductsFilter implements IQueryBuilderFilter
{
	public function getStatement(string $prefix): string
	{
		$expr = new Expr();

		return $expr->andX(
			$expr->eq("{$prefix}.removed", 'FALSE'),
			$expr->eq("{$prefix}.visible", 'TRUE')
		);
	}
}

and easily use it in FilterApplier.

$qb = $this->em->createQueryBuilder();
$qb ->select('p')
    ->from(Product::class, 'p');

$applier = new FilterApplier($qb);
$applier->filter($filter)
    ->filter(new ActiveProductsFilter());

Ordering

Using QueryOrder

QueryOrder is simple object to store ordering options for QueryBuilder.

$order = new QueryOrder(['position', 'ASC'])

$qb = $this->em->createQueryBuilder();
$qb ->select('p')
    ->from(Product::class, 'p');
    
// By calling
$qb->orderBy($order->getColumnName('p'), $order->getOrder());

// By FilterApplier
$applier->order($order);