Completed
Push — master ( b7ef6a...58a002 )
by Kirill
03:12
created

Join::getRelation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * This file is part of Hydrogen package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace RDS\Hydrogen\Criteria;
11
12
use RDS\Hydrogen\Criteria\Common\Field;
13
use RDS\Hydrogen\Processor\ProcessorInterface;
14
use RDS\Hydrogen\Query;
15
16
/**
17
 * Class Join
18
 */
19
class Join extends Criterion
20
{
21
    public const TYPE_JOIN = 0x01;
22
    public const TYPE_INNER_JOIN = 0x02;
23
    public const TYPE_LEFT_JOIN = 0x03;
24
25
    /**
26
     * @var Field
27
     */
28
    private $relation;
29
30
    /**
31
     * @var int
32
     */
33
    private $type;
34
35
    /**
36
     * @var \Closure|null
37
     */
38
    private $inner;
39
40
    /**
41
     * Relation constructor.
42
     * @param string $relation
43
     * @param Query $parent
44
     * @param int $type
45
     * @param \Closure|null $inner
46
     */
47 2
    public function __construct(Query $parent, string $relation, int $type = self::TYPE_JOIN, \Closure $inner = null)
48
    {
49 2
        parent::__construct($parent);
50
51 2
        $this->relation = $this->field($relation);
52 2
        $this->inner = $inner;
53 2
        $this->type = $type;
54 2
    }
55
56
    /**
57
     * @return Field
58
     */
59 2
    public function getRelation(): Field
60
    {
61 2
        return $this->relation;
62
    }
63
64
    /**
65
     * @return int
66
     */
67 2
    public function getType(): int
68
    {
69 2
        return $this->type;
70
    }
71
72
    /**
73
     * @return bool
74
     */
75 2
    public function hasJoinQuery(): bool
76
    {
77 2
        return $this->inner !== null;
78
    }
79
80
    /**
81
     * @param Query|null $query
82
     * @return Query
83
     */
84
    public function getJoinQuery(Query $query = null): Query
85
    {
86
        $related = $query ?? $this->query->create();
87
88
        if ($this->inner) {
89
            ($this->inner)($related);
90
        }
91
92
        return $related;
93
    }
94
95
    /**
96
     * @param ProcessorInterface $processor
97
     * @return \Generator|array
98
     */
99 2
    public function getRelations(ProcessorInterface $processor): \Generator
100
    {
101 2
        $parent = $processor->getMetadata();
102
103 2
        foreach ($this->getRelation() as $isLast => $relation) {
104 2
            yield $isLast => $from = $parent->associationMappings[$relation->getName()];
105
106 2
            $parent = $processor->getProcessor($from['targetEntity'])->getMetadata();
107
        }
108 2
    }
109
}
110