|
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\Processor\DatabaseProcessor; |
|
11
|
|
|
|
|
12
|
|
|
use Doctrine\ORM\QueryBuilder; |
|
13
|
|
|
use RDS\Hydrogen\Criteria\Common\Field; |
|
14
|
|
|
use RDS\Hydrogen\Criteria\CriterionInterface; |
|
15
|
|
|
use RDS\Hydrogen\Criteria\Relation; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Class RelationBuilder |
|
19
|
|
|
*/ |
|
20
|
|
|
class RelationBuilder extends WhereBuilder |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* @var array |
|
24
|
|
|
*/ |
|
25
|
|
|
private $relations = []; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param QueryBuilder $builder |
|
29
|
|
|
* @param CriterionInterface|Relation $relation |
|
30
|
|
|
* @return \Generator |
|
31
|
|
|
*/ |
|
32
|
|
|
public function apply($builder, CriterionInterface $relation): \Generator |
|
33
|
|
|
{ |
|
34
|
|
|
$field = $relation->getField(); |
|
35
|
|
|
$alias = $relation->getAlias(); |
|
|
|
|
|
|
36
|
|
|
|
|
37
|
|
|
foreach ($field->getChunks() as $chunk) { |
|
38
|
|
|
if (isset($this->relations[$chunk])) { |
|
39
|
|
|
$alias = $this->relations[$chunk]; |
|
40
|
|
|
continue; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$alias = $this->join($builder, $chunk, $alias); |
|
44
|
|
|
|
|
45
|
|
|
$this->relations[$chunk] = $alias; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
yield $relation->getQuery()->withAlias($alias); |
|
|
|
|
|
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param QueryBuilder $builder |
|
53
|
|
|
* @param string $child |
|
54
|
|
|
* @param string $parent |
|
55
|
|
|
* @return string |
|
56
|
|
|
*/ |
|
57
|
|
|
private function join(QueryBuilder $builder, string $child, string $parent): string |
|
58
|
|
|
{ |
|
59
|
|
|
$relation = Field::new($child)->withAlias($parent); |
|
60
|
|
|
$alias = \str_replace('.', '_', $relation->toString()); |
|
61
|
|
|
|
|
62
|
|
|
$builder->leftJoin($relation->toString(), $alias); |
|
63
|
|
|
$builder->addSelect($alias); |
|
64
|
|
|
|
|
65
|
|
|
return $alias; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: