Passed
Pull Request — master (#3367)
by Alan
04:18
created

EagerLoadingExtension::joinRelations()   F

Complexity

Conditions 32
Paths 597

Size

Total Lines 102
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 32
eloc 57
nc 597
nop 11
dl 0
loc 102
rs 0.5597
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\InvalidArgumentException;
19
use ApiPlatform\Core\Exception\PropertyNotFoundException;
20
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
21
use ApiPlatform\Core\Exception\RuntimeException;
22
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
23
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
24
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
25
use ApiPlatform\Core\Serializer\ContextTrait;
26
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
27
use ApiPlatform\Core\Serializer\SerializerContextProviderInterface;
28
use ApiPlatform\Core\Util\RequestAttributesExtractor;
29
use Doctrine\ORM\Mapping\ClassMetadataInfo;
30
use Doctrine\ORM\QueryBuilder;
31
use Symfony\Component\HttpFoundation\RequestStack;
32
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
33
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
34
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
35
36
/**
37
 * Eager loads relations.
38
 *
39
 * @author Charles Sarrazin <[email protected]>
40
 * @author Kévin Dunglas <[email protected]>
41
 * @author Antoine Bluchet <[email protected]>
42
 * @author Baptiste Meyer <[email protected]>
43
 */
44
final class EagerLoadingExtension implements ContextAwareQueryCollectionExtensionInterface, QueryItemExtensionInterface
45
{
46
    use ContextTrait;
0 ignored issues
show
introduced by
The trait ApiPlatform\Core\Serializer\ContextTrait requires some properties which are not provided by ApiPlatform\Core\Bridge\...n\EagerLoadingExtension: $query, $attributes
Loading history...
47
    use EagerLoadingTrait;
0 ignored issues
show
Bug introduced by
The trait ApiPlatform\Core\Bridge\...\Util\EagerLoadingTrait requires the property $name which is not provided by ApiPlatform\Core\Bridge\...n\EagerLoadingExtension.
Loading history...
48
49
    private $propertyNameCollectionFactory;
50
    private $propertyMetadataFactory;
51
    private $classMetadataFactory;
52
    private $maxJoins;
53
    private $serializerContextProvider;
54
    private $requestStack;
55
56
    /**
57
     * @param SerializerContextBuilderInterface|SerializerContextProviderInterface $serializerContextBuilder
58
     *
59
     * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0
60
     */
61
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, int $maxJoins = 30, bool $forceEager = true, RequestStack $requestStack = null, /* SerializerContextBuilderInterface $serializerContextProvider */$serializerContextBuilder = null, bool $fetchPartial = false, ClassMetadataFactoryInterface $classMetadataFactory = null)
62
    {
63
        if (null !== $requestStack) {
64
            @trigger_error(sprintf('Passing an instance of "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the data provider\'s context instead.', RequestStack::class), E_USER_DEPRECATED);
65
        }
66
        if (null !== $serializerContextBuilder) {
67
            @trigger_error(sprintf('Passing an instance of "%s" or "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the data provider\'s context instead.', SerializerContextBuilderInterface::class, SerializerContextProviderInterface::class), E_USER_DEPRECATED);
68
        }
69
70
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
71
        $this->propertyMetadataFactory = $propertyMetadataFactory;
72
        $this->resourceMetadataFactory = $resourceMetadataFactory;
73
        $this->classMetadataFactory = $classMetadataFactory;
74
        $this->maxJoins = $maxJoins;
75
        $this->forceEager = $forceEager;
76
        $this->fetchPartial = $fetchPartial;
77
        $this->serializerContextProvider = $serializerContextBuilder;
78
        $this->requestStack = $requestStack;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context = [])
85
    {
86
        $this->apply(true, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     *
92
     * The context may contain serialization groups which helps defining joined entities that are readable.
93
     */
94
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
95
    {
96
        $this->apply(false, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
97
    }
98
99
    private function apply(bool $collection, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, ?string $resourceClass, ?string $operationName, array $context)
100
    {
101
        if (null === $resourceClass) {
102
            throw new InvalidArgumentException('The "$resourceClass" parameter must not be null');
103
        }
104
105
        $options = [];
106
        if (null !== $operationName) {
107
            $options[($collection ? 'collection' : 'item').'_operation_name'] = $operationName;
108
        }
109
110
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
111
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
112
113
        if (!isset($context['groups']) && !isset($context['attributes'])) {
114
            $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
115
            $context += $this->getNormalizationContext($context['resource_class'] ?? $resourceClass, $contextType, $options);
116
        }
117
118
        if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) {
119
            return;
120
        }
121
122
        if (!empty($context[AbstractNormalizer::GROUPS])) {
123
            $options['serializer_groups'] = (array) $context[AbstractNormalizer::GROUPS];
124
        }
125
126
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
127
    }
128
129
    /**
130
     * Joins relations to eager load.
131
     *
132
     * @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
133
     * @param int  $joinCount    the number of joins
134
     * @param int  $currentDepth the current max depth
135
     *
136
     * @throws RuntimeException when the max number of joins has been reached
137
     */
138
    private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $options = [], array $normalizationContext = [], bool $wasLeftJoin = false, int &$joinCount = 0, int $currentDepth = null)
139
    {
140
        if ($joinCount > $this->maxJoins) {
141
            throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary with the "api_platform.eager_loading.max_joins" configuration key (https://api-platform.com/docs/core/performance/#eager-loading), or limit the maximum serialization depth using the "enable_max_depth" option of the Symfony serializer (https://symfony.com/doc/current/components/serializer.html#handling-serialization-depth).');
142
        }
143
144
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
145
        $entityManager = $queryBuilder->getEntityManager();
146
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
147
        $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null;
148
149
        foreach ($classMetadata->associationMappings as $association => $mapping) {
150
            //Don't join if max depth is enabled and the current depth limit is reached
151
            if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) {
152
                continue;
153
            }
154
155
            try {
156
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
157
            } catch (PropertyNotFoundException $propertyNotFoundException) {
158
                //skip properties not found
159
                continue;
160
            } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
161
                //skip associations that are not resource classes
162
                continue;
163
            }
164
165
            if (
166
                // Always skip extra lazy associations
167
                ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch'] ||
168
                // We don't want to interfere with doctrine on this association
169
                (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch'])
170
            ) {
171
                continue;
172
            }
173
174
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
175
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
176
                    // prepare the child context
177
                    $normalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
178
                }
179
            } else {
180
                $inAttributes = null;
181
            }
182
183
            if (
184
                (null === $fetchEager = $propertyMetadata->getAttribute('fetch_eager')) &&
185
                (null !== $fetchEager = $propertyMetadata->getAttribute('fetchEager'))
186
            ) {
187
                @trigger_error('The "fetchEager" attribute is deprecated since 2.3. Please use "fetch_eager" instead.', E_USER_DEPRECATED);
188
            }
189
190
            if (false === $fetchEager) {
191
                continue;
192
            }
193
194
            $isNotReadableLink = false === $propertyMetadata->isReadableLink();
195
            if (null === $fetchEager && (false === $propertyMetadata->isReadable() || ((null === $inAttributes && $isNotReadableLink) || (false === $inAttributes)))) {
196
                continue;
197
            }
198
199
            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
200
            if (false !== $wasLeftJoin || true === $isNullable) {
201
                $method = 'leftJoin';
202
            } else {
203
                $method = 'innerJoin';
204
            }
205
206
            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
207
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
208
            ++$joinCount;
209
210
            if (true === $fetchPartial) {
211
                try {
212
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
213
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
214
                    continue;
215
                }
216
            } else {
217
                $queryBuilder->addSelect($associationAlias);
218
            }
219
220
            // Avoid recursive joins
221
            if ($mapping['targetEntity'] === $resourceClass) {
222
                // Avoid joining the same association twice (see #1959)
223
                if (!\in_array($associationAlias, $queryBuilder->getAllAliases(), true)) {
224
                    $queryBuilder->addSelect($associationAlias);
225
                }
226
227
                continue;
228
            }
229
230
            if (isset($attributesMetadata[$association])) {
231
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
232
233
                // The current depth is the lowest max depth available in the ancestor tree.
234
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
235
                    $currentDepth = $maxDepth;
236
                }
237
            }
238
239
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $normalizationContext, 'leftJoin' === $method, $joinCount, $currentDepth);
240
        }
241
    }
242
243
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
244
    {
245
        $select = [];
246
        $entityManager = $queryBuilder->getEntityManager();
247
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
248
        if (!empty($targetClassMetadata->subClasses)) {
249
            $queryBuilder->addSelect($associationAlias);
250
251
            return;
252
        }
253
254
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
255
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
256
257
            if (true === $propertyMetadata->isIdentifier()) {
258
                $select[] = $property;
259
                continue;
260
            }
261
262
            // If it's an embedded property see below
263
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
264
                //the field test allows to add methods to a Resource which do not reflect real database fields
265
                if ($targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
266
                    $select[] = $property;
267
                }
268
269
                continue;
270
            }
271
272
            // It's an embedded property, select relevant subfields
273
            foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
274
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
275
                $propertyName = "$property.$embeddedProperty";
276
                if ($targetClassMetadata->hasField($propertyName) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
277
                    $select[] = $propertyName;
278
                }
279
            }
280
        }
281
282
        $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
283
    }
284
285
    /**
286
     * Gets the serializer context.
287
     *
288
     * @param string $contextType normalization_context or denormalization_context
289
     * @param array  $options     represents the operation name so that groups are the one of the specific operation
290
     */
291
    private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array
292
    {
293
        if (null !== $this->requestStack && null !== $this->serializerContextProvider && null !== $request = $this->requestStack->getCurrentRequest()) {
294
            if ($this->serializerContextProvider instanceof SerializerContextBuilderInterface) {
295
                return $this->serializerContextProvider->createFromRequest($request, 'normalization_context' === $contextType);
0 ignored issues
show
Deprecated Code introduced by
The function ApiPlatform\Core\Seriali...ce::createFromRequest() has been deprecated: since API Platform 2.6, use {@see \ApiPlatform\Core\Serializer\SerializerContextProviderInterface::create()} method instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

295
                return /** @scrutinizer ignore-deprecated */ $this->serializerContextProvider->createFromRequest($request, 'normalization_context' === $contextType);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
296
            }
297
            $attributes = RequestAttributesExtractor::extractAttributes($request);
298
            $operationName = $this->getOperationNameFromContext($attributes);
299
            $context = $this->addRequestContext($request, $attributes);
300
301
            return $this->serializerContextProvider->create($attributes['resource_class'], $operationName, true, $context);
302
        }
303
304
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
305
        if (isset($options['collection_operation_name'])) {
306
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
307
        } elseif (isset($options['item_operation_name'])) {
308
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
309
        } else {
310
            $context = $resourceMetadata->getAttribute($contextType);
311
        }
312
313
        return $context ?? [];
314
    }
315
}
316