Completed
Pull Request — master (#1552)
by Kévin
03:14
created

EagerLoadingExtension   F

Complexity

Total Complexity 57

Size/Duplication

Total Lines 239
Duplicated Lines 5.44 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 0
Metric Value
wmc 57
lcom 1
cbo 18
dl 13
loc 239
rs 2.9203
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A applyToCollection() 0 12 2
A applyToItem() 0 12 3
F joinRelations() 0 91 28
C addSelect() 6 35 12
C getPropertyMetadataOptions() 7 22 9
A getSerializerGroups() 0 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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\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
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
29
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
30
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
31
32
/**
33
 * Eager loads relations.
34
 *
35
 * @author Charles Sarrazin <[email protected]>
36
 * @author Kévin Dunglas <[email protected]>
37
 * @author Antoine Bluchet <[email protected]>
38
 * @author Baptiste Meyer <[email protected]>
39
 */
40
final class EagerLoadingExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
41
{
42
    use EagerLoadingTrait;
43
44
    private $propertyNameCollectionFactory;
45
    private $propertyMetadataFactory;
46
    private $classMetadataFactory;
47
    private $maxJoins;
48
    private $serializerContextBuilder;
49
    private $requestStack;
50
51
    /**
52
     * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0
53
     */
54
    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)
55
    {
56
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
57
        $this->propertyMetadataFactory = $propertyMetadataFactory;
58
        $this->resourceMetadataFactory = $resourceMetadataFactory;
59
        $this->classMetadataFactory = $classMetadataFactory;
60
        $this->maxJoins = $maxJoins;
61
        $this->forceEager = $forceEager;
62
        $this->fetchPartial = $fetchPartial;
63
        $this->serializerContextBuilder = $serializerContextBuilder;
64
        $this->requestStack = $requestStack;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
71
    {
72
        $options = null === $operationName ? [] : ['collection_operation_name' => $operationName];
73
74
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
75
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
76
        $serializerContext = $this->getPropertyMetadataOptions($resourceClass, 'normalization_context', $options);
77
78
        $groups = $this->getSerializerGroups($options, $serializerContext);
79
80
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $groups, $serializerContext);
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
        $options = null === $operationName ? [] : ['item_operation_name' => $operationName];
89
90
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
91
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
92
        $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
93
        $propertyMetadataOptions = $this->getPropertyMetadataOptions($context['resource_class'] ?? $resourceClass, $contextType, $options);
94
        $serializerGroups = $this->getSerializerGroups($options, $propertyMetadataOptions);
95
96
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $serializerGroups, $propertyMetadataOptions);
97
    }
98
99
    /**
100
     * Joins relations to eager load.
101
     *
102
     * @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
103
     * @param int  $joinCount    the number of joins
104
     * @param int  $currentDepth the current max depth
105
     *
106
     * @throws RuntimeException when the max number of joins has been reached
107
     */
108
    private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $propertyMetadataOptions = [], array $context = [], bool $wasLeftJoin = false, int &$joinCount = 0, int $currentDepth = null)
109
    {
110
        if ($joinCount > $this->maxJoins) {
111
            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.');
112
        }
113
114
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
115
        $entityManager = $queryBuilder->getEntityManager();
116
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
117
        $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null;
118
119
        foreach ($classMetadata->associationMappings as $association => $mapping) {
120
            //Don't join if max depth is enabled and the current depth limit is reached
121
            if (isset($context[AbstractObjectNormalizer::ENABLE_MAX_DEPTH]) && 0 === $currentDepth) {
122
                continue;
123
            }
124
125
            try {
126
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $propertyMetadataOptions);
127
            } catch (PropertyNotFoundException $propertyNotFoundException) {
128
                //skip properties not found
129
                continue;
130
            } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
131
                //skip associations that are not resource classes
132
                continue;
133
            }
134
135
            // We don't want to interfere with doctrine on this association
136
            if (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch']) {
137
                continue;
138
            }
139
140
            if ($useAttributes = isset($context[AbstractNormalizer::ATTRIBUTES])) {
141
                if ($inAttributes = isset($context[AbstractNormalizer::ATTRIBUTES][$association])) {
142
                    // prepare the child context
143
                    $context[AbstractNormalizer::ATTRIBUTES] = $context[AbstractNormalizer::ATTRIBUTES][$association];
144
                } else {
145
                    unset($context[AbstractNormalizer::ATTRIBUTES]);
146
                }
147
            }
148
149
            $isNotReadableLink = false === $propertyMetadata->isReadableLink();
150
            if (
151
                false === $propertyMetadata->getAttribute('fetchEager', false) &&
152
                (
153
                    false === $propertyMetadata->isReadable() ||
154
                    ((!$useAttributes && $isNotReadableLink) || ($useAttributes && !$inAttributes))
0 ignored issues
show
Bug introduced by
The variable $inAttributes does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
155
                )
156
            ) {
157
                continue;
158
            }
159
160
            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
161
            if (false !== $wasLeftJoin || true === $isNullable) {
162
                $method = 'leftJoin';
163
            } else {
164
                $method = 'innerJoin';
165
            }
166
167
            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
168
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
169
            ++$joinCount;
170
171
            if (true === $fetchPartial) {
172
                try {
173
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $propertyMetadataOptions);
174
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
175
                    continue;
176
                }
177
            } else {
178
                $queryBuilder->addSelect($associationAlias);
179
            }
180
181
            // Avoid recursion
182
            if ($mapping['targetEntity'] === $resourceClass) {
183
                $queryBuilder->addSelect($associationAlias);
184
                continue;
185
            }
186
187
            if (isset($attributesMetadata[$association])) {
188
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
189
190
                // The current depth is the lowest max depth available in the ancestor tree.
191
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
192
                    $currentDepth = $maxDepth;
193
                }
194
            }
195
196
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $propertyMetadataOptions, $context, 'leftJoin' === $method, $joinCount, $currentDepth);
197
        }
198
    }
199
200
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
201
    {
202
        $select = [];
203
        $entityManager = $queryBuilder->getEntityManager();
204
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
205
        if ($targetClassMetadata->subClasses) {
206
            $queryBuilder->addSelect($associationAlias);
207
        } else {
208
            foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
209
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
210
211
                if (true === $propertyMetadata->isIdentifier()) {
212
                    $select[] = $property;
213
                    continue;
214
                }
215
216
                //the field test allows to add methods to a Resource which do not reflect real database fields
217 View Code Duplication
                if ($targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
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...
218
                    $select[] = $property;
219
                }
220
221
                if (array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
222
                    foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
223
                        $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
224
                        $propertyName = "$property.$embeddedProperty";
225 View Code Duplication
                        if ($targetClassMetadata->hasField($propertyName) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
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...
226
                            $select[] = $propertyName;
227
                        }
228
                    }
229
                }
230
            }
231
232
            $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
233
        }
234
    }
235
236
    /**
237
     * Gets serializer context.
238
     *
239
     * @param string $contextType normalization_context or denormalization_context
240
     * @param array  $options     represents the operation name so that groups are the one of the specific operation
241
     */
242
    private function getPropertyMetadataOptions(string $resourceClass, string $contextType, array $options): array
243
    {
244
        $request = null;
245
        if (null !== $this->requestStack && null !== $this->serializerContextBuilder) {
246
            $request = $this->requestStack->getCurrentRequest();
247
        }
248
249
        if (null !== $this->serializerContextBuilder && null !== $request && !$request->attributes->get('_graphql')) {
250
            return $this->serializerContextBuilder->createFromRequest($request, 'normalization_context' === $contextType);
251
        }
252
253
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
254 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...
255
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
256
        } elseif (isset($options['item_operation_name'])) {
257
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
258
        } else {
259
            $context = $resourceMetadata->getAttribute($contextType);
260
        }
261
262
        return $context ?: [];
263
    }
264
265
    /**
266
     * Gets serializer groups if available, if not it returns the $options array.
267
     *
268
     * @param array $options represents the operation name so that groups are the one of the specific operation
269
     */
270
    private function getSerializerGroups(array $options, array $context): array
271
    {
272
        if (!empty($context[AbstractNormalizer::GROUPS])) {
273
            $options['serializer_groups'] = $context[AbstractNormalizer::GROUPS];
274
        }
275
276
        return $options;
277
    }
278
}
279