PHPackages                             silpo-tech/filter-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. silpo-tech/filter-bundle

ActiveSymfony-bundle[Search &amp; Filtering](/categories/search)

silpo-tech/filter-bundle
========================

Common Filter bundle

v2.1.0(1mo ago)11.9k—8.2%1proprietaryPHPPHP ^8.3CI passing

Since Sep 25Pushed 1mo agoCompare

[ Source](https://github.com/silpo-tech/FilterBundle)[ Packagist](https://packagist.org/packages/silpo-tech/filter-bundle)[ RSS](/packages/silpo-tech-filter-bundle/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (3)Dependencies (26)Versions (5)Used By (0)

Filter Bundle
=============

[](#filter-bundle)

[![CI](https://github.com/silpo-tech/FilterBundle/actions/workflows/ci.yml/badge.svg)](https://github.com/silpo-tech/FilterBundle/actions)[![codecov](https://camo.githubusercontent.com/05af6c6ded8729c2124b5a23da9c089a5105d63871ce464a18e80538e00ef10c/68747470733a2f2f636f6465636f762e696f2f67682f73696c706f2d746563682f46696c74657242756e646c652f67726170682f62616467652e737667)](https://codecov.io/gh/silpo-tech/FilterBundle)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)

About
-----

[](#about)

The Filter Bundle contains mapping and criteria builder

Installation
------------

[](#installation)

Require the bundle and its dependencies with composer:

```
$ composer require silpo-tech/filter-bundle
```

Register the bundle:

```
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        new FilterBundle\FilterBundle(),
    );
}
```

### Usage

[](#usage)

1. Action:

```
namespace App\Controller;

use App\DTO\Request\Location\LocationFilter;
use App\DTO\Request\Location\LocationOrder;
use FilterBundle\Request\FilterValueResolver;
use PaginatorBundle\Paginator\OffsetPaginator;
use PermissionBundle\Configuration\Permissions;
use RestBundle\Controller\RestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use FilterBundle\Annotation\FilterMapper;

class ListAction
{
    public function __construct(private readonly LocationRepository $repository)
    {
    }

    #[Route(path: 'v1/action/entities', name: ListAction::class, methods: [Request::METHOD_GET])]
    public function all(
        #[FilterMapper]
        LocationFilter $filter,
        #[FilterMapper]
        LocationSort $order,
        OffsetPaginator $offsetPaginator
     ): Response {
        return $this->createPaginatedResponse(
            $this->repository->findWithConditions($filter, $order),
            $offsetPaginator,
            LocalizedLocationDto::class
        );
    }
}
```

2. Repository method

```
namespace App\Repository;

use App\DTO\Request\Location\LocationFilter;
use App\DTO\Request\Location\LocationOrder;
use App\Entity\Location;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use FilterBundle\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
use FilterBundle\Service\ConditionBuilder;
use Hubber\LazyLib\EntityCollection;

class EntityRepository extends ServiceEntityRepository
{
    public const ALIAS = 'entity';

    public function __construct(ManagerRegistry $registry, private ConditionBuilder $conditionBuilder)
    {
        parent::__construct($registry, Entity::class);
    }

    public function findWithConditions(EntityDTOFilter $filter): EntityCollection
    {
        $queryNameGenerator = new QueryNameGenerator();

        $qb = $this->createQueryBuilder(self::ALIAS);
        $this->conditionBuilder->applyFilters($qb, $queryNameGenerator, $this->getClassName(), $filter);

        return new EntityCollection($qb);
    }
}
```

### Filter DTO example:

[](#filter-dto-example)

```
namespace App\Dto\Request\Entity;

use FilterBundle\Annotation\ApiFilter;
use FilterBundle\Bridge\Doctrine\Orm\BooleanFilter;use FilterBundle\Bridge\Doctrine\Orm\SearchFilter;
use FilterBundle\Bridge\Doctrine\Orm\LocaleFilter;
use FilterBundle\Bridge\Doctrine\Orm\OrderFilter;
use FilterBundle\Validator\Constraints\ValidDateRange;
use FilterBundle\Validator\Constraints\DateRangeBeforeGreaterThanAfter;
use FilterBundle\Validator\Constraints\DateRangeBeforeNotEqualsAfter;
use Symfony\Component\Validator\Constraints as Assert;

 #[ApiFilter(LocaleFilter::class, property: 'translations.locale')]
class EntityDTOFilter
{
    #[ApiFilter(SearchFilter::class, property: 'parents.id', strategy: SearchFilter::STRATEGY_EXACT)]
    #[Assert\Uuid]
    /** @var string */
    public $parentId;

    #[Assert\Sequentially(constraints: [
        new Assert\Type(type: 'string'),
        new Assert\Uuid(versions: [Assert\Uuid::V6_SORTABLE]),
    ])]
    #[ApiFilter(SearchFilter::class, property: 'nullableId', strategy: 'exact')]
    #[ApiFilter(NullFilter::class, property: 'nullableId')]
    /** @var string|null */
    public $nullableId = null;

    #[ApiFilter(BooleanFilter::class)]
    /** @var boolean */
    public $active = true;

    #[Assert\Sequentially(
        constraints: [
            new Assert\NotBlank(),
            new Assert\Choice(callback: [EntityStatus::class, 'getChoices'], multiple: true)
        ]
    )]
    #[ApiFilter(SearchFilter::class, property: 'status', strategy: SearchFilter::STRATEGY_EXACT)]
    /** @var array */
    public $status = [];

    #[ApiFilter(DateFilter::class, property: 'createdAt')]
    #[ValidDateRange(format: 'Y-m')]
    #[DateRangeBeforeGreaterThanAfter]
    #[DateRangeBeforeNotEqualsAfter]
    /** @var array */
    public $createdAt = [];

    #[Assert\Type('array')]
    #[ApiSort(
        filterClass: OrderFilter::class,
        map: ['id' => 'id', 'status' => 'status', 'createdAt' => 'createdAt', 'updatedAt' => 'updatedAt']
    )]
    /** @var string[] */
    public $sort = ['-id'];
}
```

### Search Filter

[](#search-filter)

If Doctrine ORM or MongoDB ODM support is enabled, adding filters is as easy as registering a filter service in the `api/config/services.yaml` file and adding an attribute to your resource configuration.

The search filter supports `exact`, `partial`, `start`, `end`, and `word_start` matching strategies:

- `exact` strategy uses `IN (...)` to search for fields that contain `value1, value2, ..., valueN`.
- `partial` strategy uses `LIKE %text%` to search for fields that contain `text`.
- `start` strategy uses `LIKE text%` to search for fields that start with `text`.
- `end` strategy uses `LIKE %text` to search for fields that end with `text`.
- `word_start` strategy uses `LIKE text% OR LIKE % text%` to search for fields that contain words starting with `text`.

Prepend the letter `i` to the filter if you want it to be case insensitive. For example `ipartial` or `iexact`. Note that this will use the `LOWER` function and **will** impact performance **if there is no proper index**.

Case insensitivity may already be enforced at the database level depending on the [collation](https://en.wikipedia.org/wiki/Collation)used. If you are using MySQL, note that the commonly used `utf8_unicode_ci` collation (and its sibling `utf8mb4_unicode_ci`) are already case-insensitive, as indicated by the `_ci` part in their names.

You can dynamically change the strategy to filters from the client, for this behavior your dto must implement StrategyInterface: `?filter[title:istart]=Ukrainian`

Example syntax for exact strategy: `?filter[status][0]=new&filter[status][1]=completed`

### Date Filter

[](#date-filter)

Usage syntax: `?filter[createdAt][from]=2022-05&filter[createdAt][to]=2022-06`

#### Managing `null` Values

[](#managing-null-values)

The date filter is able to deal with date properties having `null` values. Four behaviors are available at the property level of the filter via the `arguments` parameter:

DescriptionStrategy to setUse the default behavior of the DBMS`null` (default)Exclude items`exclude_null`Consider items as oldest`include_null_before`Consider items as youngest`include_null_after`Always include items`include_null_before_and_after`To configure null management for a date property, pass the `nullManagement` key in the `arguments` array of the `#[ApiFilter]` attribute:

```
use FilterBundle\Annotation\ApiFilter;
use FilterBundle\Bridge\Doctrine\Orm\DateFilter;

class EntityDTOFilter
{
    #[ApiFilter(DateFilter::class, property: 'deletedAt', arguments: ['nullManagement' => 'exclude_null'])]
    /** @var array */
    public $deletedAt = [];

    #[ApiFilter(DateFilter::class, property: 'archivedAt', arguments: ['nullManagement' => 'include_null_before_and_after'])]
    /** @var array */
    public $archivedAt = [];
}
```

**Behavior details:**

- `exclude_null` — adds `IS NOT NULL` condition, completely excluding records where the date field is `null`.
- `include_null_before` — when filtering with `to`/`strictly_to`, records with `null` are included in the results (treated as oldest).
- `include_null_after` — when filtering with `from`/`strictly_from`, records with `null` are included in the results (treated as youngest).
- `include_null_before_and_after` — records with `null` are always included regardless of the filter direction.

You can also combine `nullManagement` with other DateFilter arguments like `compareDateToDateTime` or `convertToTz`:

```
#[ApiFilter(DateFilter::class, property: 'createdAt', arguments: [
    'nullManagement' => 'include_null_after',
    'convertToTz' => 'UTC',
])]
public $createdAt = [];
```

### Order Filter (Sorting)

[](#order-filter-sorting)

The order filter allows to sort a collection against the given properties.

Syntax: `?filter[sort][0]=-createdAt&filter[sort][0]=updatedAt`

By default, whenever the query does not specify the direction explicitly (e.g.: `?filter[sort][0]=-createdAt`), filters will not be applied unless you configure a default order direction to use.

### Constraints

[](#constraints)

#### ValidDateRange

[](#validdaterange)

Validates that given array value is a valid date range, e.g. property is an array with two keys: **from**, **to**; array values should date string of valid format, default format is **Y-m-d**

#### Basic usage

[](#basic-usage)

```
use FilterBundle\Validator\Constraints\DateRange;

class FilterDTO
{
    #[DateRange(format: DateTimeInterface::ATOM)]
    /** @var string[] */
    public $createdAt = [];
}
```

```
use FilterBundle\Validator\Constraints\DateRange;

class FilterDTO
{
    #[DateRange(
        format: DateTimeInterface::ATOM,
        min: '+1 sec',
        max: '+23 day 4 hour',
    )]
    /** @var string[] */
    public $createdAt = [];
}
```

#### Options

[](#options)

**format**

Defines date string format

**invalidDateTimeMessage**

Message that will be shown if **from** or **to** values are not valid date string

**invalidDateRangeMessage**

Message that will be shown if **from** is greater than **to**

**min**

If provided additional check will be performed to check **to** is greater than **from** for at least **min**value. Value should be valid DateInterval string with leading plus sign, e.g. `+1 sec`, `+2 hour 3 min`.

**max**

If provided additional check will be performed to check **to** is greater than **from** for at most **max**value. Value should be valid DateInterval string with leading plus sign, e.g. `+1 sec`, `+2 hour 3 min`.

**minMessage**

Message that will be shown if **to** is not greater than **from** for at least **min** value

**maxMessage**

Message that will be shown if **to** is greater than **from** for more than **max** value

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance92

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~122 days

Total

3

Last Release

39d ago

Major Versions

v1.0.0 → v2.0.02025-10-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/f9891deddc63cb60dd472af17aee913a559f29defbe861135037dbbdf99449a6?d=identicon)[food-tech-devs](/maintainers/food-tech-devs)

---

Top Contributors

[![panayotovyura](https://avatars.githubusercontent.com/u/8473688?v=4)](https://github.com/panayotovyura "panayotovyura (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/silpo-tech-filter-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/silpo-tech-filter-bundle/health.svg)](https://phpackages.com/packages/silpo-tech-filter-bundle)
```

###  Alternatives

[easycorp/easyadmin-bundle

Admin generator for Symfony applications

4.3k17.9M387](/packages/easycorp-easyadmin-bundle)[2lenet/crudit-bundle

The easy like Crud'it Bundle.

1616.4k14](/packages/2lenet-crudit-bundle)[chameleon-system/chameleon-base

The Chameleon System core.

1028.6k5](/packages/chameleon-system-chameleon-base)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M577](/packages/shopware-core)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k5.9M737](/packages/sylius-sylius)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

9421.6k61](/packages/open-dxp-opendxp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
