Skip to content

Commit

Permalink
Internal: Add API filter to perform match-against searches - refs BT#…
Browse files Browse the repository at this point in the history
…22036
  • Loading branch information
AngelFQC committed Nov 14, 2024
1 parent 4196227 commit afcc0fe
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions config/packages/doctrine.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ doctrine:
string_functions:
MONTH: DoctrineExtensions\Query\Mysql\Month
YEAR: DoctrineExtensions\Query\Mysql\Year
MATCH: DoctrineExtensions\Query\Mysql\MatchAgainst
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
Expand Down
60 changes: 60 additions & 0 deletions src/CoreBundle/Filter/MatchSearchFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/* For licensing terms, see /license.txt */

declare(strict_types=1);

namespace Chamilo\CoreBundle\Filter;

use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;
use InvalidArgumentException;

class MatchSearchFilter extends AbstractFilter
{
protected function filterProperty(
string $property,
$value,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
?Operation $operation = null,
array $context = []
): void {
if ('search' !== $property) {
return;
}

if (empty($value)) {
throw new InvalidArgumentException('The property must not be empty.');
}

$alias = $queryBuilder->getRootAliases()[0];
$valueParameter = ':'.$queryNameGenerator->generateParameterName($property);

$matchFields = [];

foreach (array_keys($this->properties) as $field) {
$matchFields[] = "$alias.$field";
}

$queryBuilder
->andWhere('MATCH ('.implode(', ', $matchFields).') AGAINST ('.$valueParameter.' IN BOOLEAN MODE) > 0')
->setParameter($valueParameter, '+"'.$value.'"')
;
}

public function getDescription(string $resourceClass): array
{
return [
'search' => [
'property' => null,
'type' => 'string',
'required' => false,
'description' => 'It does a "Search OR" using `LIKE %text%` to search for fields that contain `text`',
],
];
}
}

0 comments on commit afcc0fe

Please sign in to comment.