IndexBy::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
/**
4
 * This file is part of the Happyr Doctrine Specification package.
5
 *
6
 * (c) Tobias Nyholm <[email protected]>
7
 *     Kacper Gunia <[email protected]>
8
 *     Peter Gribanov <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Happyr\DoctrineSpecification\Query;
15
16
use Doctrine\ORM\Query\QueryException;
17
use Doctrine\ORM\QueryBuilder;
18
use Happyr\DoctrineSpecification\Operand\Field;
19
20
/**
21
 * Class IndexBy.
22
 */
23
class IndexBy implements QueryModifier
24
{
25
    /**
26
     * @var Field
27
     */
28
    private $field;
29
30
    /**
31
     * @var string|null
32
     */
33
    private $dqlAlias;
34
35
    /**
36
     * @param Field|string $field    Field name for indexing
37
     * @param string|null  $dqlAlias DQL alias of field
38
     */
39
    public function __construct($field, $dqlAlias = null)
40
    {
41
        if (!($field instanceof Field)) {
42
            $field = new Field($field);
43
        }
44
        $this->field = $field;
45
        $this->dqlAlias = $dqlAlias;
46
    }
47
48
    /**
49
     * @param QueryBuilder $qb
50
     * @param string       $dqlAlias
51
     *
52
     * @throws QueryException
53
     */
54
    public function modify(QueryBuilder $qb, $dqlAlias)
55
    {
56
        if (null !== $this->dqlAlias) {
57
            $dqlAlias = $this->dqlAlias;
58
        }
59
60
        // doctrine/orm < 2.5
61
        if (!method_exists($qb, 'indexBy')) {
62
            throw new \RuntimeException('IndexBy query modifier require doctrine/orm >= 2.5');
63
        }
64
65
        $qb->indexBy($dqlAlias, $this->field->transform($qb, $dqlAlias));
66
    }
67
}
68