forked from chamilo/chamilo-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Internal: Add API filter to perform match-against searches - refs BT#…
…22036
- Loading branch information
Showing
2 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`', | ||
], | ||
]; | ||
} | ||
} |