Completed
Push — 1.0 ( b7886a...4c0b42 )
by Peter
07:48 queued 11s
created

Comparison::getParameterName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Happyr\DoctrineSpecification\Filter;
4
5
use Doctrine\ORM\QueryBuilder;
6
use Doctrine\ORM\Query\Expr\Comparison as DoctrineComparison;
7
use Happyr\DoctrineSpecification\Exception\InvalidArgumentException;
8
use Happyr\DoctrineSpecification\Operand\ArgumentToOperandConverter;
9
use Happyr\DoctrineSpecification\Operand\Operand;
10
11
/**
12
 * Comparison class.
13
 *
14
 * This is used when you need to compare two values
15
 */
16
class Comparison implements Filter
17
{
18
    const EQ = '=';
19
20
    const NEQ = '<>';
21
22
    const LT = '<';
23
24
    const LTE = '<=';
25
26
    const GT = '>';
27
28
    const GTE = '>=';
29
30
    /**
31
     * @var Operand|string
32
     */
33
    protected $field;
34
35
    /**
36
     * @var Operand|string
37
     */
38
    protected $value;
39
40
    /**
41
     * @var string
42
     */
43
    protected $dqlAlias;
44
45
    /**
46
     * @var array
47
     */
48
    private static $operators = array(
49
        self::EQ, self::NEQ,
50
        self::LT, self::LTE,
51
        self::GT, self::GTE,
52
    );
53
54
    /**
55
     * @var string
56
     */
57
    private $operator;
58
59
    /**
60
     * Make sure the $field has a value equals to $value.
61
     *
62
     * @param string         $operator
63
     * @param Operand|string $field
64
     * @param Operand|mixed  $value
65
     * @param string|null    $dqlAlias
66
     *
67
     * @throws InvalidArgumentException
68
     */
69
    public function __construct($operator, $field, $value, $dqlAlias = null)
70
    {
71
        if (!in_array($operator, self::$operators)) {
72
            throw new InvalidArgumentException(sprintf(
73
                '"%s" is not a valid comparison operator. Valid operators are: "%s"',
74
                $operator,
75
                implode(', ', self::$operators)
76
            ));
77
        }
78
79
        $this->operator = $operator;
80
        $this->field = $field;
81
        $this->value = $value;
82
        $this->dqlAlias = $dqlAlias;
83
    }
84
85
    /**
86
     * @param QueryBuilder $qb
87
     * @param string       $dqlAlias
88
     *
89
     * @return string
90
     */
91
    public function getFilter(QueryBuilder $qb, $dqlAlias)
92
    {
93
        if (null !== $this->dqlAlias) {
94
            $dqlAlias = $this->dqlAlias;
95
        }
96
97
        $field = ArgumentToOperandConverter::toField($this->field);
98
        $value = ArgumentToOperandConverter::toValue($this->value);
99
100
        return (string) new DoctrineComparison(
101
            $field->transform($qb, $dqlAlias),
102
            $this->operator,
103
            $value->transform($qb, $dqlAlias)
104
        );
105
    }
106
}
107