1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* (c) Christian Gripp <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Core23\Doctrine\Manager\ORM; |
13
|
|
|
|
14
|
|
|
use Doctrine\ORM\Query\Expr\Composite; |
15
|
|
|
use Doctrine\ORM\Query\Expr\Orx; |
16
|
|
|
use Doctrine\ORM\QueryBuilder; |
17
|
|
|
|
18
|
|
|
trait SearchQueryTrait |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Creates a like search for a given field and text values. |
22
|
|
|
* |
23
|
|
|
* @param QueryBuilder $qb |
24
|
|
|
* @param string $field |
25
|
|
|
* @param array $values |
26
|
|
|
* @param bool $strict |
27
|
|
|
* |
28
|
|
|
* @return Composite |
29
|
|
|
*/ |
30
|
|
|
final protected function searchWhere(QueryBuilder $qb, string $field, array $values, bool $strict = false): Composite |
31
|
|
|
{ |
32
|
|
|
$orx = $qb->expr()->orX(); |
33
|
|
|
foreach ($values as $index => $word) { |
34
|
|
|
$orx->add(sprintf('%s = :name'.$index, $field)); |
35
|
|
|
$qb->setParameter('name'.$index, $word); |
36
|
|
|
|
37
|
|
|
if (!$strict) { |
38
|
|
|
$this->buildLikeExpressions($qb, $orx, $field, $word, $index); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return $orx; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param QueryBuilder $qb |
47
|
|
|
* @param Orx $orx |
48
|
|
|
* @param string $field |
49
|
|
|
* @param string $word |
50
|
|
|
* @param int $index |
51
|
|
|
*/ |
52
|
|
|
private function buildLikeExpressions(QueryBuilder $qb, Orx $orx, string $field, string $word, int $index): void |
53
|
|
|
{ |
54
|
|
|
$orx->add(sprintf('%s LIKE :name'.$index.'_any', $field)); |
55
|
|
|
$orx->add(sprintf('%s LIKE :name'.$index.'_pre', $field)); |
56
|
|
|
$orx->add(sprintf('%s LIKE :name'.$index.'_suf', $field)); |
57
|
|
|
|
58
|
|
|
$qb->setParameter('name'.$index.'_any', '% '.$word.' %'); |
59
|
|
|
$qb->setParameter('name'.$index.'_pre', '% '.$word); |
60
|
|
|
$qb->setParameter('name'.$index.'_suf', $word.' %'); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|