-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PropertyHelperTrait.php
81 lines (68 loc) · 2.69 KB
/
PropertyHelperTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Doctrine\Orm;
use ApiPlatform\Doctrine\Orm\Util\QueryBuilderHelper;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Exception\InvalidArgumentException;
use Doctrine\ORM\Mapping\ClassMetadata as ClassMetadataInfo;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\Mapping\ClassMetadata;
/**
* Helper trait regarding a property in an entity using the resource metadata.
*
* @author Kévin Dunglas <[email protected]>
* @author Théo FIDRY <[email protected]>
*/
trait PropertyHelperTrait
{
abstract protected function getManagerRegistry(): ManagerRegistry;
/**
* Splits the given property into parts.
*/
abstract protected function splitPropertyParts(string $property, string $resourceClass): array;
/**
* Gets class metadata for the given resource.
*/
protected function getClassMetadata(string $resourceClass): ClassMetadata
{
$manager = $this
->getManagerRegistry()
->getManagerForClass($resourceClass);
if ($manager) {
return $manager->getClassMetadata($resourceClass);
}
return new ClassMetadataInfo($resourceClass);
}
/**
* Adds the necessary joins for a nested property.
*
* @throws InvalidArgumentException If property is not nested
*
* @return array An array where the first element is the join $alias of the leaf entity,
* the second element is the $field name
* the third element is the $associations array
*/
protected function addJoinsForNestedProperty(string $property, string $rootAlias, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $joinType): array
{
$propertyParts = $this->splitPropertyParts($property, $resourceClass);
$parentAlias = $rootAlias;
$alias = null;
foreach ($propertyParts['associations'] as $association) {
$alias = QueryBuilderHelper::addJoinOnce($queryBuilder, $queryNameGenerator, $parentAlias, $association, $joinType);
$parentAlias = $alias;
}
if (null === $alias) {
throw new InvalidArgumentException(sprintf('Cannot add joins for property "%s" - property is not nested.', $property));
}
return [$alias, $propertyParts['field'], $propertyParts['associations']];
}
}