Completed
Push — master ( 4030be...df6e71 )
by Tobias
10:01
created

In::getFilter()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 14
nc 4
nop 2
1
<?php
2
3
namespace Happyr\DoctrineSpecification\Filter;
4
5
use Doctrine\ORM\QueryBuilder;
6
use Happyr\DoctrineSpecification\ValueConverter;
7
8
class In implements Filter
9
{
10
    /**
11
     * @var string field
12
     */
13
    protected $field;
14
15
    /**
16
     * @var mixed value
17
     */
18
    protected $value;
19
20
    /**
21
     * @var string dqlAlias
22
     */
23
    protected $dqlAlias;
24
25
    /**
26
     * Make sure the $field has a value equals to $value.
27
     *
28
     * @param string $field
29
     * @param mixed  $value
30
     * @param string $dqlAlias
31
     */
32
    public function __construct($field, $value, $dqlAlias = null)
33
    {
34
        $this->field = $field;
35
        $this->value = $value;
36
        $this->dqlAlias = $dqlAlias;
37
    }
38
39
    /**
40
     * @param QueryBuilder $qb
41
     * @param string       $dqlAlias
42
     *
43
     * @return string
44
     */
45
    public function getFilter(QueryBuilder $qb, $dqlAlias)
46
    {
47
        if ($this->dqlAlias !== null) {
48
            $dqlAlias = $this->dqlAlias;
49
        }
50
51
        $value = $this->value;
52
        if (is_array($value)) {
53
            foreach ($value as $k => $v) {
54
                $value[$k] = ValueConverter::convertToDatabaseValue($v, $qb);
55
            }
56
        } else {
57
            $value = ValueConverter::convertToDatabaseValue($value, $qb);
58
        }
59
60
        $paramName = $this->getParameterName($qb);
61
        $qb->setParameter($paramName, $value);
62
63
        return (string) $qb->expr()->in(
64
            sprintf('%s.%s', $dqlAlias, $this->field),
65
            sprintf(':%s', $paramName)
66
        );
67
    }
68
69
    /**
70
     * Get a good unique parameter name.
71
     *
72
     * @param QueryBuilder $qb
73
     *
74
     * @return string
75
     */
76
    protected function getParameterName(QueryBuilder $qb)
77
    {
78
        return sprintf('in_%d', $qb->getParameters()->count());
79
    }
80
}
81