Completed
Push — master ( ec7e38...159154 )
by Kévin
05:47 queued 02:39
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 = 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
            if (
136
                // Always skip extra lazy associations
137
                ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch'] ||
138
                // We don't want to interfere with doctrine on this association
139
                (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch'])
140
            ) {
141
                continue;
142
            }
143
144
            if (isset($context[AbstractNormalizer::ATTRIBUTES])) {
145
                if ($inAttributes = isset($context[AbstractNormalizer::ATTRIBUTES][$association])) {
146
                    // prepare the child context
147
                    $context[AbstractNormalizer::ATTRIBUTES] = $context[AbstractNormalizer::ATTRIBUTES][$association];
148
                } else {
149
                    unset($context[AbstractNormalizer::ATTRIBUTES]);
150
                }
151
            } else {
152
                $inAttributes = null;
153
            }
154
155
            $isNotReadableLink = false === $propertyMetadata->isReadableLink();
156
            if (
157
                false === $propertyMetadata->getAttribute('fetchEager', false) &&
158
                (
159
                    false === $propertyMetadata->isReadable() ||
160
                    ((null === $inAttributes && $isNotReadableLink) || (false === $inAttributes))
161
                )
162
            ) {
163
                continue;
164
            }
165
166
            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
167
            if (false !== $wasLeftJoin || true === $isNullable) {
168
                $method = 'leftJoin';
169
            } else {
170
                $method = 'innerJoin';
171
            }
172
173
            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
174
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
175
            ++$joinCount;
176
177
            if (true === $fetchPartial) {
178
                try {
179
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $propertyMetadataOptions);
180
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
181
                    continue;
182
                }
183
            } else {
184
                $queryBuilder->addSelect($associationAlias);
185
            }
186
187
            // Avoid recursion
188
            if ($mapping['targetEntity'] === $resourceClass) {
189
                $queryBuilder->addSelect($associationAlias);
190
                continue;
191
            }
192
193
            if (isset($attributesMetadata[$association])) {
194
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
195
196
                // The current depth is the lowest max depth available in the ancestor tree.
197
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
198
                    $currentDepth = $maxDepth;
199
                }
200
            }
201
202
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $propertyMetadataOptions, $context, 'leftJoin' === $method, $joinCount, $currentDepth);
203
        }
204
    }
205
206
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
207
    {
208
        $select = [];
209
        $entityManager = $queryBuilder->getEntityManager();
210
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
211
        if ($targetClassMetadata->subClasses) {
212
            $queryBuilder->addSelect($associationAlias);
213
        } else {
214
            foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
215
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
216
217
                if (true === $propertyMetadata->isIdentifier()) {
218
                    $select[] = $property;
219
                    continue;
220
                }
221
222
                //the field test allows to add methods to a Resource which do not reflect real database fields
223 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...
224
                    $select[] = $property;
225
                }
226
227
                if (array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
228
                    foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
229
                        $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
230
                        $propertyName = "$property.$embeddedProperty";
231 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...
232
                            $select[] = $propertyName;
233
                        }
234
                    }
235
                }
236
            }
237
238
            $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
239
        }
240
    }
241
242
    /**
243
     * Gets serializer context.
244
     *
245
     * @param string $contextType normalization_context or denormalization_context
246
     * @param array  $options     represents the operation name so that groups are the one of the specific operation
247
     */
248
    private function getPropertyMetadataOptions(string $resourceClass, string $contextType, array $options): array
249
    {
250
        $request = null;
251
        if (null !== $this->requestStack && null !== $this->serializerContextBuilder) {
252
            $request = $this->requestStack->getCurrentRequest();
253
        }
254
255
        if (null !== $this->serializerContextBuilder && null !== $request && !$request->attributes->get('_graphql')) {
256
            return $this->serializerContextBuilder->createFromRequest($request, 'normalization_context' === $contextType);
257
        }
258
259
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
260 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...
261
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
262
        } elseif (isset($options['item_operation_name'])) {
263
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
264
        } else {
265
            $context = $resourceMetadata->getAttribute($contextType);
266
        }
267
268
        return $context ?: [];
269
    }
270
271
    /**
272
     * Gets serializer groups if available, if not it returns the $options array.
273
     *
274
     * @param array $options represents the operation name so that groups are the one of the specific operation
275
     */
276
    private function getSerializerGroups(array $options, array $context): array
277
    {
278
        if (!empty($context[AbstractNormalizer::GROUPS])) {
279
            $options['serializer_groups'] = $context[AbstractNormalizer::GROUPS];
280
        }
281
282
        return $options;
283
    }
284
}
285