Passed
Push — master ( 46e57d...ec86a4 )
by Christian
01:49
created

SearchQueryTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 43
rs 10
c 0
b 0
f 0

2 Methods

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