• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 6148660584

11 Sep 2023 03:40PM UTC coverage: 37.077% (-0.1%) from 37.185%
6148660584

push

github

soyuka
chore(symfony): security after validate when validator installed

10090 of 27214 relevant lines covered (37.08%)

19.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.12
/src/Doctrine/Orm/Extension/EagerLoadingExtension.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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\Doctrine\Orm\Extension;
15

16
use ApiPlatform\Doctrine\Orm\Util\QueryBuilderHelper;
17
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
18
use ApiPlatform\Exception\InvalidArgumentException;
19
use ApiPlatform\Exception\PropertyNotFoundException;
20
use ApiPlatform\Exception\ResourceClassNotFoundException;
21
use ApiPlatform\Exception\RuntimeException;
22
use ApiPlatform\Metadata\Operation;
23
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use Doctrine\ORM\Mapping\ClassMetadata;
26
use Doctrine\ORM\Mapping\ClassMetadataInfo;
27
use Doctrine\ORM\Query\Expr\Join;
28
use Doctrine\ORM\Query\Expr\Select;
29
use Doctrine\ORM\QueryBuilder;
30
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
31
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
32
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
33

34
/**
35
 * Eager loads relations.
36
 *
37
 * @author Charles Sarrazin <charles@sarraz.in>
38
 * @author Kévin Dunglas <dunglas@gmail.com>
39
 * @author Antoine Bluchet <soyuka@gmail.com>
40
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
41
 */
42
final class EagerLoadingExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
43
{
44
    public function __construct(private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly int $maxJoins = 30, private readonly bool $forceEager = true, private readonly bool $fetchPartial = false, private readonly ?ClassMetadataFactoryInterface $classMetadataFactory = null)
45
    {
46
    }
93✔
47

48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, Operation $operation = null, array $context = []): void
52
    {
53
        $this->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
60✔
54
    }
55

56
    /**
57
     * The context may contain serialization groups which helps defining joined entities that are readable.
58
     */
59
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void
60
    {
61
        $this->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
36✔
62
    }
63

64
    private function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, ?string $resourceClass, ?Operation $operation, array $context): void
65
    {
66
        if (null === $resourceClass) {
93✔
67
            throw new InvalidArgumentException('The "$resourceClass" parameter must not be null');
×
68
        }
69

70
        $options = [];
93✔
71

72
        $forceEager = $operation?->getForceEager() ?? $this->forceEager;
93✔
73
        $fetchPartial = $operation?->getFetchPartial() ?? $this->fetchPartial;
93✔
74

75
        if (!isset($context['groups']) && !isset($context['attributes'])) {
93✔
76
            $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
66✔
77
            if ($operation) {
66✔
78
                $context += 'denormalization_context' === $contextType ? ($operation->getDenormalizationContext() ?? []) : ($operation->getNormalizationContext() ?? []);
66✔
79
            }
80
        }
81

82
        if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) {
93✔
83
            return;
24✔
84
        }
85

86
        if (!empty($context[AbstractNormalizer::GROUPS])) {
69✔
87
            $options['serializer_groups'] = (array) $context[AbstractNormalizer::GROUPS];
69✔
88
        }
89

90
        if ($operation && $normalizationGroups = $operation->getNormalizationContext()['groups'] ?? null) {
69✔
91
            $options['normalization_groups'] = $normalizationGroups;
54✔
92
        }
93

94
        if ($operation && $denormalizationGroups = $operation->getDenormalizationContext()['groups'] ?? null) {
69✔
95
            $options['denormalization_groups'] = $denormalizationGroups;
3✔
96
        }
97

98
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
69✔
99
    }
100

101
    /**
102
     * Joins relations to eager load.
103
     *
104
     * @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
105
     * @param int  $joinCount    the number of joins
106
     * @param int  $currentDepth the current max depth
107
     *
108
     * @throws RuntimeException when the max number of joins has been reached
109
     */
110
    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, string $parentAssociation = null): void
111
    {
112
        if ($joinCount > $this->maxJoins) {
69✔
113
            throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary with the "api_platform.eager_loading.max_joins" configuration key (https://api-platform.com/docs/core/performance/#eager-loading), or limit the maximum serialization depth using the "enable_max_depth" option of the Symfony serializer (https://symfony.com/doc/current/components/serializer.html#handling-serialization-depth).');
3✔
114
        }
115

116
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
69✔
117
        $entityManager = $queryBuilder->getEntityManager();
69✔
118
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
69✔
119
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($resourceClass)->getAttributesMetadata();
69✔
120

121
        foreach ($classMetadata->associationMappings as $association => $mapping) {
69✔
122
            // Don't join if max depth is enabled and the current depth limit is reached
123
            if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) {
60✔
124
                continue;
3✔
125
            }
126

127
            try {
128
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
60✔
129
            } catch (PropertyNotFoundException) {
6✔
130
                // skip properties not found
131
                continue;
3✔
132
                // @phpstan-ignore-next-line indeed this can be thrown by the SerializerPropertyMetadataFactory
133
            } catch (ResourceClassNotFoundException) {
3✔
134
                // skip associations that are not resource classes
135
                continue;
3✔
136
            }
137

138
            if (
139
                // Always skip extra lazy associations
140
                ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch']
54✔
141
                // We don't want to interfere with doctrine on this association
142
                || (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch'])
54✔
143
            ) {
144
                continue;
12✔
145
            }
146

147
            // prepare the child context
148
            $childNormalizationContext = $normalizationContext;
45✔
149
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
45✔
150
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
6✔
151
                    $childNormalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
4✔
152
                }
153
            } else {
154
                $inAttributes = null;
39✔
155
            }
156

157
            $fetchEager = $propertyMetadata->getFetchEager();
45✔
158
            $uriTemplate = $propertyMetadata->getUriTemplate();
45✔
159

160
            if (false === $fetchEager || null !== $uriTemplate) {
45✔
161
                continue;
6✔
162
            }
163

164
            if (true !== $fetchEager && (false === $propertyMetadata->isReadable() || false === $inAttributes)) {
39✔
165
                continue;
6✔
166
            }
167

168
            // Avoid joining back to the parent that we just came from, but only on *ToOne relations
169
            if (
170
                null !== $parentAssociation
36✔
171
                && isset($mapping['inversedBy'])
36✔
172
                && $mapping['inversedBy'] === $parentAssociation
36✔
173
                && $mapping['type'] & ClassMetadata::TO_ONE
36✔
174
            ) {
175
                continue;
×
176
            }
177

178
            $existingJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, $parentAlias, $association);
36✔
179

180
            if (null !== $existingJoin) {
36✔
181
                $associationAlias = $existingJoin->getAlias();
6✔
182
                $isLeftJoin = Join::LEFT_JOIN === $existingJoin->getJoinType();
6✔
183
            } else {
184
                $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
30✔
185
                $isLeftJoin = false !== $wasLeftJoin || true === $isNullable;
30✔
186
                $method = $isLeftJoin ? 'leftJoin' : 'innerJoin';
30✔
187

188
                $associationAlias = $queryNameGenerator->generateJoinAlias($association);
30✔
189
                $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
30✔
190
                ++$joinCount;
30✔
191
            }
192

193
            if (true === $fetchPartial) {
36✔
194
                try {
195
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
24✔
196
                } catch (ResourceClassNotFoundException) {
3✔
197
                    continue;
10✔
198
                }
199
            } else {
200
                $this->addSelectOnce($queryBuilder, $associationAlias);
12✔
201
            }
202

203
            // Avoid recursive joins for self-referencing relations
204
            if ($mapping['targetEntity'] === $resourceClass) {
33✔
205
                continue;
×
206
            }
207

208
            // Only join the relation's relations recursively if it's a readableLink
209
            if (true !== $fetchEager && (true !== $propertyMetadata->isReadableLink())) {
33✔
210
                continue;
6✔
211
            }
212

213
            if (isset($attributesMetadata[$association])) {
27✔
214
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
3✔
215

216
                // The current depth is the lowest max depth available in the ancestor tree.
217
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
3✔
218
                    $currentDepth = $maxDepth;
3✔
219
                }
220
            }
221

222
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $childNormalizationContext, $isLeftJoin, $joinCount, $currentDepth, $association);
27✔
223
        }
224
    }
225

226
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions): void
227
    {
228
        $select = [];
24✔
229
        $entityManager = $queryBuilder->getEntityManager();
24✔
230
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
24✔
231
        if (!empty($targetClassMetadata->subClasses)) {
24✔
232
            $this->addSelectOnce($queryBuilder, $associationAlias);
3✔
233

234
            return;
3✔
235
        }
236

237
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
24✔
238
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
21✔
239

240
            if (true === $propertyMetadata->isIdentifier()) {
21✔
241
                $select[] = $property;
15✔
242
                continue;
15✔
243
            }
244

245
            // If it's an embedded property see below
246
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
18✔
247
                $isFetchable = $propertyMetadata->isFetchable();
18✔
248
                // the field test allows to add methods to a Resource which do not reflect real database fields
249
                if ($targetClassMetadata->hasField($property) && (true === $isFetchable || $propertyMetadata->isReadable())) {
18✔
250
                    $select[] = $property;
12✔
251
                }
252

253
                continue;
18✔
254
            }
255

256
            // It's an embedded property, select relevant subfields
257
            foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
6✔
258
                $isFetchable = $propertyMetadata->isFetchable();
6✔
259
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
6✔
260
                $propertyName = "$property.$embeddedProperty";
6✔
261
                if ($targetClassMetadata->hasField($propertyName) && (true === $isFetchable || $propertyMetadata->isReadable())) {
6✔
262
                    $select[] = $propertyName;
6✔
263
                }
264
            }
265
        }
266

267
        $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
21✔
268
    }
269

270
    private function addSelectOnce(QueryBuilder $queryBuilder, string $alias): void
271
    {
272
        $existingSelects = array_reduce($queryBuilder->getDQLPart('select') ?? [], fn ($existing, $dqlSelect) => ($dqlSelect instanceof Select) ? array_merge($existing, $dqlSelect->getParts()) : $existing, []);
15✔
273

274
        if (!\in_array($alias, $existingSelects, true)) {
15✔
275
            $queryBuilder->addSelect($alias);
15✔
276
        }
277
    }
278
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc