Passed
Pull Request — 2.1 (#1729)
by Antoine
04:12 queued 01:10
created

EagerLoadingExtension   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 242
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 59
dl 0
loc 242
rs 4.5454
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
B apply() 0 20 7
B getNormalizationContext() 0 17 6
A applyToItem() 0 3 1
C addSelect() 0 33 12
A __construct() 0 18 3
A applyToCollection() 0 3 1
F joinRelations() 0 99 29

How to fix   Complexity   

Complex Class

Complex classes like EagerLoadingExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EagerLoadingExtension, and based on these observations, apply Extract Interface, too.

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\SerializerContextBuilderInterface;
26
use Doctrine\ORM\Mapping\ClassMetadataInfo;
27
use Doctrine\ORM\QueryBuilder;
28
use Symfony\Component\HttpFoundation\RequestStack;
29
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
30
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
31
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
32
33
/**
34
 * Eager loads relations.
35
 *
36
 * @author Charles Sarrazin <[email protected]>
37
 * @author Kévin Dunglas <[email protected]>
38
 * @author Antoine Bluchet <[email protected]>
39
 * @author Baptiste Meyer <[email protected]>
40
 */
41
final class EagerLoadingExtension implements ContextAwareQueryCollectionExtensionInterface, QueryItemExtensionInterface
42
{
43
    use EagerLoadingTrait;
44
45
    private $propertyNameCollectionFactory;
46
    private $propertyMetadataFactory;
47
    private $classMetadataFactory;
48
    private $maxJoins;
49
    private $serializerContextBuilder;
50
    private $requestStack;
51
52
    /**
53
     * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0
54
     */
55
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, int $maxJoins = 30, bool $forceEager = true, RequestStack $requestStack = null, SerializerContextBuilderInterface $serializerContextBuilder = null, bool $fetchPartial = false, ClassMetadataFactoryInterface $classMetadataFactory = null)
56
    {
57
        if (null !== $this->requestStack) {
58
            @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);
59
        }
60
        if (null !== $this->serializerContextBuilder) {
61
            @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.', SerializerContextBuilderInterface::class), E_USER_DEPRECATED);
62
        }
63
64
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
65
        $this->propertyMetadataFactory = $propertyMetadataFactory;
66
        $this->resourceMetadataFactory = $resourceMetadataFactory;
67
        $this->classMetadataFactory = $classMetadataFactory;
68
        $this->maxJoins = $maxJoins;
69
        $this->forceEager = $forceEager;
70
        $this->fetchPartial = $fetchPartial;
71
        $this->serializerContextBuilder = $serializerContextBuilder;
72
        $this->requestStack = $requestStack;
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context = [])
79
    {
80
        $this->apply(true, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
81
    }
82
83
    /**
84
     * The context may contain serialization groups which helps defining joined entities that are readable.
85
     */
86
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
87
    {
88
        $this->apply(false, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
89
    }
90
91
    private function apply(bool $collection, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context)
92
    {
93
        if (null === $resourceClass) {
94
            throw new InvalidArgumentException('The "$resourceClass" parameter must not be null');
95
        }
96
97
        $options = [];
98
        if (null !== $operationName) {
99
            $options[($collection ? 'collection' : 'item').'_operation_name'] = $operationName;
100
        }
101
102
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
103
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
104
105
        if (!isset($context['groups']) && !isset($context['attributes'])) {
106
            $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
107
            $context += $this->getNormalizationContext($context['resource_class'] ?? $resourceClass, $contextType, $options);
108
        }
109
110
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
111
    }
112
113
    /**
114
     * Joins relations to eager load.
115
     *
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
     * @param int  $currentDepth the current max depth
119
     *
120
     * @throws RuntimeException when the max number of joins has been reached
121
     */
122
    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)
123
    {
124
        if ($joinCount > $this->maxJoins) {
125
            throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary, or use the "max_depth" option of the Symfony serializer.');
126
        }
127
128
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
129
        $entityManager = $queryBuilder->getEntityManager();
130
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
131
        $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null;
132
133
        if (!empty($normalizationContext[AbstractNormalizer::GROUPS])) {
134
            $options['serializer_groups'] = $normalizationContext[AbstractNormalizer::GROUPS];
135
        }
136
137
        foreach ($classMetadata->associationMappings as $association => $mapping) {
138
            //Don't join if max depth is enabled and the current depth limit is reached
139
            if (0 === $currentDepth && isset($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH])) {
140
                continue;
141
            }
142
143
            try {
144
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
145
            } catch (PropertyNotFoundException $propertyNotFoundException) {
146
                //skip properties not found
147
                continue;
148
            } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
149
                //skip associations that are not resource classes
150
                continue;
151
            }
152
153
            if (
154
                // Always skip extra lazy associations
155
                ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch'] ||
156
                // We don't want to interfere with doctrine on this association
157
                (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch'])
158
            ) {
159
                continue;
160
            }
161
162
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
163
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
164
                    // prepare the child context
165
                    $normalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
166
                } else {
167
                    unset($normalizationContext[AbstractNormalizer::ATTRIBUTES]);
168
                }
169
            } else {
170
                $inAttributes = null;
171
            }
172
173
            $isNotReadableLink = false === $propertyMetadata->isReadableLink();
174
            if (
175
                false === $propertyMetadata->getAttribute('fetchEager', false) &&
176
                (
177
                    false === $propertyMetadata->isReadable() ||
178
                    ((null === $inAttributes && $isNotReadableLink) || (false === $inAttributes))
179
                )
180
            ) {
181
                continue;
182
            }
183
184
            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
185
            if (false !== $wasLeftJoin || true === $isNullable) {
186
                $method = 'leftJoin';
187
            } else {
188
                $method = 'innerJoin';
189
            }
190
191
            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
192
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
193
            ++$joinCount;
194
195
            if (true === $fetchPartial) {
196
                try {
197
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
198
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
199
                    continue;
200
                }
201
            } else {
202
                $queryBuilder->addSelect($associationAlias);
203
            }
204
205
            // Avoid recursion
206
            if ($mapping['targetEntity'] === $resourceClass) {
207
                $queryBuilder->addSelect($associationAlias);
208
                continue;
209
            }
210
211
            if (isset($attributesMetadata[$association])) {
212
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
213
214
                // The current depth is the lowest max depth available in the ancestor tree.
215
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
216
                    $currentDepth = $maxDepth;
217
                }
218
            }
219
220
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $normalizationContext, 'leftJoin' === $method, $joinCount, $currentDepth);
221
        }
222
    }
223
224
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
225
    {
226
        $select = [];
227
        $entityManager = $queryBuilder->getEntityManager();
228
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
229
        if ($targetClassMetadata->subClasses) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $targetClassMetadata->subClasses of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
230
            $queryBuilder->addSelect($associationAlias);
231
        } else {
232
            foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
233
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
234
235
                if (true === $propertyMetadata->isIdentifier()) {
236
                    $select[] = $property;
237
                    continue;
238
                }
239
240
                //the field test allows to add methods to a Resource which do not reflect real database fields
241
                if ($targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
242
                    $select[] = $property;
243
                }
244
245
                if (array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
246
                    foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
247
                        $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
248
                        $propertyName = "$property.$embeddedProperty";
249
                        if ($targetClassMetadata->hasField($propertyName) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
250
                            $select[] = $propertyName;
251
                        }
252
                    }
253
                }
254
            }
255
256
            $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
257
        }
258
    }
259
260
    /**
261
     * Gets serializer context.
262
     *
263
     * @param string $contextType normalization_context or denormalization_context
264
     * @param array  $options     represents the operation name so that groups are the one of the specific operation
265
     */
266
    private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array
267
    {
268
        $request = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $request is dead and can be removed.
Loading history...
269
        if (null !== $this->requestStack && null !== $this->serializerContextBuilder && null !== $request = $this->requestStack->getCurrentRequest()) {
270
            return $this->serializerContextBuilder->createFromRequest($request, 'normalization_context' === $contextType);
271
        }
272
273
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
274
        if (isset($options['collection_operation_name'])) {
275
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
276
        } elseif (isset($options['item_operation_name'])) {
277
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
278
        } else {
279
            $context = $resourceMetadata->getAttribute($contextType);
280
        }
281
282
        return $context ?? [];
283
    }
284
}
285