Completed
Push — master ( 29c52c...d78909 )
by Kévin
03:18
created

EagerLoadingExtension::addSelect()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
c 0
b 0
f 0
rs 6.7272
cc 7
eloc 15
nc 5
nop 4
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Extension;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\EagerLoadingTrait;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
18
use ApiPlatform\Core\Exception\PropertyNotFoundException;
19
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
20
use ApiPlatform\Core\Exception\RuntimeException;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
24
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
25
use Doctrine\ORM\Mapping\ClassMetadataInfo;
26
use Doctrine\ORM\QueryBuilder;
27
use Symfony\Component\HttpFoundation\RequestStack;
28
29
/**
30
 * Eager loads relations.
31
 *
32
 * @author Charles Sarrazin <[email protected]>
33
 * @author Kévin Dunglas <[email protected]>
34
 * @author Antoine Bluchet <[email protected]>
35
 * @author Baptiste Meyer <[email protected]>
36
 */
37
final class EagerLoadingExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
38
{
39
    use EagerLoadingTrait;
40
41
    private $propertyNameCollectionFactory;
42
    private $propertyMetadataFactory;
43
    private $maxJoins;
44
    private $serializerContextBuilder;
45
    private $requestStack;
46
47
    /**
48
     * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0
49
     */
50
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, int $maxJoins = 30, bool $forceEager = true, RequestStack $requestStack = null, SerializerContextBuilderInterface $serializerContextBuilder = null, bool $fetchPartial = false)
51
    {
52
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
53
        $this->propertyMetadataFactory = $propertyMetadataFactory;
54
        $this->resourceMetadataFactory = $resourceMetadataFactory;
55
        $this->maxJoins = $maxJoins;
56
        $this->forceEager = $forceEager;
57
        $this->fetchPartial = $fetchPartial;
58
        $this->serializerContextBuilder = $serializerContextBuilder;
59
        $this->requestStack = $requestStack;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
66
    {
67
        $options = [];
68
69
        if (null !== $operationName) {
70
            $options = ['collection_operation_name' => $operationName];
71
        }
72
73
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
74
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
75
76
        $groups = $this->getSerializerGroups($resourceClass, $options, 'normalization_context');
77
78
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $groups);
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     * The context may contain serialization groups which helps defining joined entities that are readable.
84
     */
85
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
86
    {
87
        $options = [];
88
89
        if (null !== $operationName) {
90
            $options = ['item_operation_name' => $operationName];
91
        }
92
93
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
94
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
95
96
        if (isset($context['groups'])) {
97
            $groups = ['serializer_groups' => $context['groups']];
98
        } elseif (isset($context['resource_class'])) {
99
            $groups = $this->getSerializerGroups($context['resource_class'], $options, isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context');
100
        } else {
101
            $groups = $this->getSerializerGroups($resourceClass, $options, 'normalization_context');
102
        }
103
104
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $groups);
105
    }
106
107
    /**
108
     * Joins relations to eager load.
109
     *
110
     * @param QueryBuilder                $queryBuilder
111
     * @param QueryNameGeneratorInterface $queryNameGenerator
112
     * @param string                      $resourceClass
113
     * @param bool                        $forceEager
114
     * @param string                      $parentAlias
115
     * @param array                       $propertyMetadataOptions
116
     * @param bool                        $wasLeftJoin             if the relation containing the new one had a left join, we have to force the new one to left join too
117
     * @param int                         $joinCount               the number of joins
118
     *
119
     * @throws RuntimeException when the max number of joins has been reached
120
     */
121
    private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $propertyMetadataOptions = [], bool $wasLeftJoin = false, int &$joinCount = 0)
122
    {
123
        if ($joinCount > $this->maxJoins) {
124
            throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary.');
125
        }
126
127
        $entityManager = $queryBuilder->getEntityManager();
128
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
129
130
        foreach ($classMetadata->associationMappings as $association => $mapping) {
131
            try {
132
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $propertyMetadataOptions);
133
            } catch (PropertyNotFoundException $propertyNotFoundException) {
134
                //skip properties not found
135
                continue;
136
            } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
137
                //skip associations that are not resource classes
138
                continue;
139
            }
140
141
            // We don't want to interfere with doctrine on this association
142
            if (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch']) {
143
                continue;
144
            }
145
146
            if (false === $propertyMetadata->isReadableLink() || false === $propertyMetadata->isReadable()) {
147
                continue;
148
            }
149
150
            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
151
            if (false !== $wasLeftJoin || true === $isNullable) {
152
                $method = 'leftJoin';
153
            } else {
154
                $method = 'innerJoin';
155
            }
156
157
            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
158
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
159
            ++$joinCount;
160
161
            if (true === $fetchPartial) {
162
                try {
163
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $propertyMetadataOptions);
164
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
165
                    continue;
166
                }
167
            } else {
168
                $queryBuilder->addSelect($associationAlias);
169
            }
170
171
            // Avoid recursion
172
            if ($mapping['targetEntity'] === $resourceClass) {
173
                $queryBuilder->addSelect($associationAlias);
174
                continue;
175
            }
176
177
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $propertyMetadataOptions, $method === 'leftJoin', $joinCount);
178
        }
179
    }
180
181
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
182
    {
183
        $select = [];
184
        $entityManager = $queryBuilder->getEntityManager();
185
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
186
        if ($targetClassMetadata->subClasses) {
187
            $queryBuilder->addSelect($associationAlias);
188
        } else {
189
            foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
190
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
191
192
                if (true === $propertyMetadata->isIdentifier()) {
193
                    $select[] = $property;
194
                    continue;
195
                }
196
197
                //the field test allows to add methods to a Resource which do not reflect real database fields
198
                if (true === $targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || true === $propertyMetadata->isReadable())) {
199
                    $select[] = $property;
200
                }
201
            }
202
203
            $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
204
        }
205
    }
206
207
    /**
208
     * Gets serializer groups if available, if not it returns the $options array.
209
     *
210
     * @param string $resourceClass
211
     * @param array  $options       represents the operation name so that groups are the one of the specific operation
212
     * @param string $context       normalization_context or denormalization_context
213
     *
214
     * @return array
215
     */
216
    private function getSerializerGroups(string $resourceClass, array $options, string $context): array
217
    {
218
        $request = null;
219
220
        if (null !== $this->requestStack && null !== $this->serializerContextBuilder) {
221
            $request = $this->requestStack->getCurrentRequest();
222
        }
223
224
        if (null !== $this->serializerContextBuilder && null !== $request) {
225
            $contextFromRequest = $this->serializerContextBuilder->createFromRequest($request, $context === 'normalization_context');
226
227
            if (isset($contextFromRequest['groups'])) {
228
                return ['serializer_groups' => $contextFromRequest['groups']];
229
            }
230
        }
231
232
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
233
234 View Code Duplication
        if (isset($options['collection_operation_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
235
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $context, null, true);
236
        } elseif (isset($options['item_operation_name'])) {
237
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $context, null, true);
238
        } else {
239
            $context = $resourceMetadata->getAttribute($context);
240
        }
241
242
        if (empty($context['groups'])) {
243
            return $options;
244
        }
245
246
        return ['serializer_groups' => $context['groups']];
247
    }
248
}
249