Completed
Push — update-typo-in-interface ( 9a3ea2...ed634c )
by Samuel
03:08
created

EagerLoadingExtension::getSerializerGroups()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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