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

api-platform / core / 7044846563

30 Nov 2023 10:01AM UTC coverage: 58.804% (-0.02%) from 58.821%
7044846563

push

github

web-flow
chore: support symfony 7 (#6009)

* chore: symfony 7

* Add `$buildDir` to `CachePoolClearerCacheWarmer::warmUp()`

Symfony 7 adds a new parameter `$buildDir` to
`WarmableInterface::warmUp()`, so that the method signature of
`CachePoolClearerCacheWarmer::warmUp()` needs to be updated.

* more

---------

Co-authored-by: Tac Tacelosky <tacman@gmail.com>
Co-authored-by: Yannick Ihmels <yannick@ihmels.org>

2 of 3 new or added lines in 3 files covered. (66.67%)

8 existing lines in 2 files now uncovered.

10874 of 18492 relevant lines covered (58.8%)

19.82 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
    }
60✔
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);
38✔
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);
24✔
62
    }
63

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

70
        $options = [];
60✔
71

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

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

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

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

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

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

98
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
44✔
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) {
44✔
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).');
2✔
114
        }
115

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

121
        foreach ($classMetadata->associationMappings as $association => $mapping) {
44✔
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)) {
38✔
124
                continue;
2✔
125
            }
126

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

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

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

157
            $fetchEager = $propertyMetadata->getFetchEager();
28✔
158

159
            if (false === $fetchEager) {
28✔
160
                continue;
2✔
161
            }
162

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

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

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

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

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

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

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

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

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

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

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

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

234
            return;
2✔
235
        }
236

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

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

245
            // If it's an embedded property see below
246
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
12✔
247
                $isFetchable = $propertyMetadata->isFetchable();
12✔
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())) {
12✔
250
                    $select[] = $property;
8✔
251
                }
252

253
                continue;
12✔
254
            }
255

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

267
        $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
14✔
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, []);
10✔
273

274
        if (!\in_array($alias, $existingSelects, true)) {
10✔
275
            $queryBuilder->addSelect($alias);
10✔
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