Completed
Pull Request — master (#1546)
by Kévin
05:42 queued 02:35
created

EagerLoadingExtension::addSelect()   C

Complexity

Conditions 12
Paths 11

Size

Total Lines 35
Code Lines 21

Duplication

Lines 6
Ratio 17.14 %

Importance

Changes 0
Metric Value
dl 6
loc 35
rs 5.1612
c 0
b 0
f 0
cc 12
eloc 21
nc 11
nop 4

How to fix   Complexity   

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:

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 = [];
73
74
        if (null !== $operationName) {
75
            $options = ['collection_operation_name' => $operationName];
76
        }
77
78
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
79
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
80
        $serializerContext = $this->getSerializerContext($resourceClass, 'normalization_context', $options);
81
82
        $groups = $this->getPropertyMetadataOptions($options, $serializerContext);
83
84
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $groups, $serializerContext);
85
    }
86
87
    /**
88
     * The context may contain serialization groups which helps defining joined entities that are readable.
89
     */
90
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
91
    {
92
        $options = [];
93
94
        if (null !== $operationName) {
95
            $options = ['item_operation_name' => $operationName];
96
        }
97
98
        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
99
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);
100
        $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
101
        $serializerContext = $this->getSerializerContext($context['resource_class'] ?? $resourceClass, $contextType, $options);
102
        $serializerOptions = $this->getPropertyMetadataOptions($options, $serializerContext);
103
104
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $serializerOptions, $serializerContext);
105
    }
106
107
    /**
108
     * Joins relations to eager load.
109
     *
110
     * @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
111
     * @param int  $joinCount    the number of joins
112
     * @param int  $currentDepth the current max depth
113
     *
114
     * @throws RuntimeException when the max number of joins has been reached
115
     */
116
    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)
117
    {
118
        if ($joinCount > $this->maxJoins) {
119
            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.');
120
        }
121
122
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
123
        $entityManager = $queryBuilder->getEntityManager();
124
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
125
        $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null;
126
127
        foreach ($classMetadata->associationMappings as $association => $mapping) {
128
            //Don't join if max depth is enabled and the current depth limit is reached
129
            if (isset($context[AbstractObjectNormalizer::ENABLE_MAX_DEPTH]) && 0 === $currentDepth) {
130
                continue;
131
            }
132
133
            try {
134
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $propertyMetadataOptions);
135
            } catch (PropertyNotFoundException $propertyNotFoundException) {
136
                //skip properties not found
137
                continue;
138
            } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
139
                //skip associations that are not resource classes
140
                continue;
141
            }
142
143
            // We don't want to interfere with doctrine on this association
144
            if (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch']) {
145
                continue;
146
            }
147
148
            if ($inAttributes = isset($context[AbstractNormalizer::ATTRIBUTES][$association])) {
149
                // prepare the child context
150
                $context[AbstractNormalizer::ATTRIBUTES] = $context[AbstractNormalizer::ATTRIBUTES][$association];
151
            } else {
152
                unset($context[AbstractNormalizer::ATTRIBUTES]);
153
            }
154
155
            if (((!$inAttributes && false === $propertyMetadata->isReadableLink()) || false === $propertyMetadata->isReadable()) && false === $propertyMetadata->getAttribute('fetchEager', false)) {
156
                continue;
157
            }
158
159
            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
160
            if (false !== $wasLeftJoin || true === $isNullable) {
161
                $method = 'leftJoin';
162
            } else {
163
                $method = 'innerJoin';
164
            }
165
166
            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
167
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
168
            ++$joinCount;
169
170
            if (true === $fetchPartial) {
171
                try {
172
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $propertyMetadataOptions);
173
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
174
                    continue;
175
                }
176
            } else {
177
                $queryBuilder->addSelect($associationAlias);
178
            }
179
180
            // Avoid recursion
181
            if ($mapping['targetEntity'] === $resourceClass) {
182
                $queryBuilder->addSelect($associationAlias);
183
                continue;
184
            }
185
186
            if (isset($attributesMetadata[$association])) {
187
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
188
189
                // The current depth is the lowest max depth available in the ancestor tree.
190
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
191
                    $currentDepth = $maxDepth;
192
                }
193
            }
194
195
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $propertyMetadataOptions, $context, 'leftJoin' === $method, $joinCount, $currentDepth);
196
        }
197
    }
198
199
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
200
    {
201
        $select = [];
202
        $entityManager = $queryBuilder->getEntityManager();
203
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
204
        if ($targetClassMetadata->subClasses) {
205
            $queryBuilder->addSelect($associationAlias);
206
        } else {
207
            foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
208
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
209
210
                if (true === $propertyMetadata->isIdentifier()) {
211
                    $select[] = $property;
212
                    continue;
213
                }
214
215
                //the field test allows to add methods to a Resource which do not reflect real database fields
216 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...
217
                    $select[] = $property;
218
                }
219
220
                if (array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
221
                    foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
222
                        $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
223
                        $propertyName = "$property.$embeddedProperty";
224 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...
225
                            $select[] = $propertyName;
226
                        }
227
                    }
228
                }
229
            }
230
231
            $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
232
        }
233
    }
234
235
    /**
236
     * Gets serializer context.
237
     *
238
     * @param string $contextType normalization_context or denormalization_context
239
     * @param array  $options     represents the operation name so that groups are the one of the specific operation
240
     */
241
    private function getSerializerContext(string $resourceClass, string $contextType, array $options): array
242
    {
243
        $request = null;
244
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
255 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...
256
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
257
        } elseif (isset($options['item_operation_name'])) {
258
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
259
        } else {
260
            $context = $resourceMetadata->getAttribute($contextType);
261
        }
262
263
        return $context ?: [];
264
    }
265
266
    /**
267
     * Gets serializer groups if available, if not it returns the $options array.
268
     *
269
     * @param array $options represents the operation name so that groups are the one of the specific operation
270
     */
271
    private function getPropertyMetadataOptions(array $options, array $context): array
272
    {
273
        if (!empty($context[AbstractNormalizer::GROUPS])) {
274
            $options['serializer_groups'] = $context[AbstractNormalizer::GROUPS];
275
        }
276
277
        return $options;
278
    }
279
}
280