Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions src/Doctrine/Odm/Filter/StartSearchFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Odm\Filter;

use ApiPlatform\Doctrine\Common\Filter\OpenApiFilterTrait;
use ApiPlatform\Doctrine\Odm\NestedPropertyHelperTrait;
use ApiPlatform\Metadata\BackwardCompatibleFilterDescriptionTrait;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ODM\MongoDB\Aggregation\Builder;
use MongoDB\BSON\Regex;

/**
* Filters the collection by the beginning of a string property, using a regular expression anchored at the start.
*/
final class StartSearchFilter implements FilterInterface, OpenApiParameterFilterInterface
{
use BackwardCompatibleFilterDescriptionTrait;
use NestedPropertyHelperTrait;
use OpenApiFilterTrait;

public function __construct(private readonly bool $caseSensitive = true)
{
}

public function apply(Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void
{
$parameter = $context['parameter'];

if (null === $parameter->getProperty()) {
throw new InvalidArgumentException(\sprintf('The filter parameter with key "%s" must specify a property. Please provide the property explicitly.', $parameter->getKey()));
}

$property = $parameter->getProperty();
$values = $parameter->getValue();
$match = $context['match'] = $context['match'] ??
$aggregationBuilder
->matchExpr();
$operator = $context['operator'] ?? 'addAnd';

$matchField = $this->addNestedParameterLookups($property, $aggregationBuilder, $parameter, false, $context);

if (!is_iterable($values)) {
$escapedValue = preg_quote($values, '/');
$match->{$operator}(
$aggregationBuilder->matchExpr()->field($matchField)->equals(new Regex('^'.$escapedValue, $this->caseSensitive ? '' : 'i'))
);

return;
}

$or = $aggregationBuilder->matchExpr();
foreach ($values as $value) {
$escapedValue = preg_quote($value, '/');

$or->addOr(
$aggregationBuilder->matchExpr()
->field($matchField)
->equals(new Regex('^'.$escapedValue, $this->caseSensitive ? '' : 'i'))
);
}

$match->{$operator}($or);
}
}
82 changes: 82 additions & 0 deletions src/Doctrine/Odm/Filter/WordStartSearchFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Odm\Filter;

use ApiPlatform\Doctrine\Common\Filter\OpenApiFilterTrait;
use ApiPlatform\Doctrine\Odm\NestedPropertyHelperTrait;
use ApiPlatform\Metadata\BackwardCompatibleFilterDescriptionTrait;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ODM\MongoDB\Aggregation\Builder;
use MongoDB\BSON\Regex;

/**
* Filters the collection by a word boundary prefix, matching documents that contain a word starting with the value,
* using a regular expression anchored at the start of the string or at a word boundary.
*/
final class WordStartSearchFilter implements FilterInterface, OpenApiParameterFilterInterface
{
use BackwardCompatibleFilterDescriptionTrait;
use NestedPropertyHelperTrait;
use OpenApiFilterTrait;

public function __construct(private readonly bool $caseSensitive = true)
{
}

public function apply(Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void
{
$parameter = $context['parameter'];

if (null === $parameter->getProperty()) {
throw new InvalidArgumentException(\sprintf('The filter parameter with key "%s" must specify a property. Please provide the property explicitly.', $parameter->getKey()));
}

$property = $parameter->getProperty();
$values = $parameter->getValue();
$match = $context['match'] = $context['match'] ??
$aggregationBuilder
->matchExpr();
$operator = $context['operator'] ?? 'addAnd';

$matchField = $this->addNestedParameterLookups($property, $aggregationBuilder, $parameter, false, $context);

if (!is_iterable($values)) {
$match->{$operator}(
$aggregationBuilder->matchExpr()->field($matchField)->equals($this->createRegex($values))
);

return;
}

$or = $aggregationBuilder->matchExpr();
foreach ($values as $value) {
$or->addOr(
$aggregationBuilder->matchExpr()
->field($matchField)
->equals($this->createRegex($value))
);
}

$match->{$operator}($or);
}

private function createRegex(string $value): Regex
{
$escapedValue = preg_quote($value, '/');

return new Regex('(^'.$escapedValue.'|\s'.$escapedValue.')', $this->caseSensitive ? '' : 'i');
}
}
83 changes: 83 additions & 0 deletions src/Doctrine/Orm/Filter/StartSearchFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

use ApiPlatform\Doctrine\Common\Filter\OpenApiFilterTrait;
use ApiPlatform\Doctrine\Orm\NestedPropertyHelperTrait;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\BackwardCompatibleFilterDescriptionTrait;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;

/**
* Filters the collection by the beginning of a string property, using a `LIKE 'value%'` clause.
*/
final class StartSearchFilter implements FilterInterface, OpenApiParameterFilterInterface
{
use BackwardCompatibleFilterDescriptionTrait;
use NestedPropertyHelperTrait;
use OpenApiFilterTrait;

public function __construct(private readonly bool $caseSensitive = false)
{
}

public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
{
$parameter = $context['parameter'];

if (null === $parameter->getProperty()) {
throw new InvalidArgumentException(\sprintf('The filter parameter with key "%s" must specify a property. Please provide the property explicitly.', $parameter->getKey()));
}

$property = $parameter->getProperty();
$alias = $queryBuilder->getRootAliases()[0];
[$alias, $property] = $this->addNestedParameterJoins($property, $alias, $queryBuilder, $queryNameGenerator, $parameter);
$field = $alias.'.'.$property;
$values = $parameter->getValue();

if (!is_iterable($values)) {
$parameterName = $queryNameGenerator->generateParameterName($property);
$queryBuilder->setParameter($parameterName, $this->formatLikeValue($values));

$likeExpression = $this->caseSensitive
? $field.' LIKE :'.$parameterName.' ESCAPE \'\\\''
: 'LOWER('.$field.') LIKE LOWER(:'.$parameterName.') ESCAPE \'\\\'';
$queryBuilder->{$context['whereClause'] ?? 'andWhere'}($likeExpression);

return;
}

$likeExpressions = [];
foreach ($values as $val) {
$parameterName = $queryNameGenerator->generateParameterName($property);
$likeExpressions[] = $this->caseSensitive
? $field.' LIKE :'.$parameterName.' ESCAPE \'\\\''
: 'LOWER('.$field.') LIKE LOWER(:'.$parameterName.') ESCAPE \'\\\'';

$queryBuilder->setParameter($parameterName, $this->formatLikeValue($val));
}

$queryBuilder->{$context['whereClause'] ?? 'andWhere'}(
$queryBuilder->expr()->orX(...$likeExpressions)
);
}

private function formatLikeValue(string $value): string
{
return addcslashes($value, '\\%_').'%';
}
}
92 changes: 92 additions & 0 deletions src/Doctrine/Orm/Filter/WordStartSearchFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

use ApiPlatform\Doctrine\Common\Filter\OpenApiFilterTrait;
use ApiPlatform\Doctrine\Orm\NestedPropertyHelperTrait;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\BackwardCompatibleFilterDescriptionTrait;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;

/**
* Filters the collection by a word boundary prefix, matching fields that contain a word starting with the value,
* using a `LIKE 'value%' OR LIKE '% value%'` clause.
*/
final class WordStartSearchFilter implements FilterInterface, OpenApiParameterFilterInterface
{
use BackwardCompatibleFilterDescriptionTrait;
use NestedPropertyHelperTrait;
use OpenApiFilterTrait;

public function __construct(private readonly bool $caseSensitive = false)
{
}

public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
{
$parameter = $context['parameter'];

if (null === $parameter->getProperty()) {
throw new InvalidArgumentException(\sprintf('The filter parameter with key "%s" must specify a property. Please provide the property explicitly.', $parameter->getKey()));
}

$property = $parameter->getProperty();
$alias = $queryBuilder->getRootAliases()[0];
[$alias, $property] = $this->addNestedParameterJoins($property, $alias, $queryBuilder, $queryNameGenerator, $parameter);
$field = $alias.'.'.$property;
$values = $parameter->getValue();

if (!is_iterable($values)) {
$values = [$values];
}

$expressions = [];
foreach ($values as $val) {
$startName = $queryNameGenerator->generateParameterName($property);
$wordName = $queryNameGenerator->generateParameterName($property);

$expressions[] = $queryBuilder->expr()->orX(
$this->createLikeExpression($field, $startName),
$this->createLikeExpression($field, $wordName),
);

$queryBuilder->setParameter($startName, $this->formatStartValue($val));
$queryBuilder->setParameter($wordName, $this->formatWordValue($val));
}

$queryBuilder->{$context['whereClause'] ?? 'andWhere'}(
$queryBuilder->expr()->orX(...$expressions)
);
}

private function createLikeExpression(string $field, string $parameterName): string
{
return $this->caseSensitive
? $field.' LIKE :'.$parameterName.' ESCAPE \'\\\''
: 'LOWER('.$field.') LIKE LOWER(:'.$parameterName.') ESCAPE \'\\\'';
}

private function formatStartValue(string $value): string
{
return addcslashes($value, '\\%_').'%';
}

private function formatWordValue(string $value): string
{
return '% '.addcslashes($value, '\\%_').'%';
}
}
16 changes: 16 additions & 0 deletions tests/Fixtures/TestBundle/Document/Chicken.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
use ApiPlatform\Doctrine\Odm\Filter\IriFilter;
use ApiPlatform\Doctrine\Odm\Filter\OrFilter;
use ApiPlatform\Doctrine\Odm\Filter\PartialSearchFilter;
use ApiPlatform\Doctrine\Odm\Filter\StartSearchFilter;
use ApiPlatform\Doctrine\Odm\Filter\WordStartSearchFilter;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
Expand Down Expand Up @@ -55,6 +57,20 @@
filter: new EndSearchFilter(true),
property: 'name',
),
'nameStart' => new QueryParameter(
filter: new StartSearchFilter(false),
property: 'name',
),
'nameStartNoProperty' => new QueryParameter(filter: new StartSearchFilter()),
'nameStartSensitive' => new QueryParameter(
filter: new StartSearchFilter(true),
property: 'name',
),
'nameWordStart' => new QueryParameter(
filter: new WordStartSearchFilter(false),
property: 'name',
),
'nameWordStartNoProperty' => new QueryParameter(filter: new WordStartSearchFilter()),
'autocomplete' => new QueryParameter(filter: new FreeTextQueryFilter(new OrFilter(new ExactFilter())), properties: ['name', 'ean']),
'q' => new QueryParameter(filter: new FreeTextQueryFilter(new PartialSearchFilter()), properties: ['name', 'ean']),
'qmixed' => new QueryParameter(filter: new FreeTextQueryFilter([
Expand Down
16 changes: 16 additions & 0 deletions tests/Fixtures/TestBundle/Entity/Chicken.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
use ApiPlatform\Doctrine\Orm\Filter\IriFilter;
use ApiPlatform\Doctrine\Orm\Filter\OrFilter;
use ApiPlatform\Doctrine\Orm\Filter\PartialSearchFilter;
use ApiPlatform\Doctrine\Orm\Filter\StartSearchFilter;
use ApiPlatform\Doctrine\Orm\Filter\WordStartSearchFilter;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
Expand Down Expand Up @@ -55,6 +57,20 @@
filter: new EndSearchFilter(true),
property: 'name',
),
'nameStart' => new QueryParameter(
filter: new StartSearchFilter(),
property: 'name',
),
'nameStartNoProperty' => new QueryParameter(filter: new StartSearchFilter()),
'nameStartSensitive' => new QueryParameter(
filter: new StartSearchFilter(true),
property: 'name',
),
'nameWordStart' => new QueryParameter(
filter: new WordStartSearchFilter(),
property: 'name',
),
'nameWordStartNoProperty' => new QueryParameter(filter: new WordStartSearchFilter()),
'autocomplete' => new QueryParameter(filter: new FreeTextQueryFilter(new OrFilter(new ExactFilter())), properties: ['name', 'ean']),
'q' => new QueryParameter(filter: new FreeTextQueryFilter(new PartialSearchFilter()), properties: ['name', 'ean']),
'qmixed' => new QueryParameter(filter: new FreeTextQueryFilter([
Expand Down
Loading
Loading