Completed
Pull Request — master (#1619)
by Kévin
02:55
created

EagerLoadingExtension::applyToCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 5
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->serializerContextBuilder) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

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