Completed
Pull Request — master (#904)
by Antoine
03:34
created

SubresourceDataProvider::getSubresource()   D

Complexity

Conditions 18
Paths 94

Size

Total Lines 104
Code Lines 55

Duplication

Lines 14
Ratio 13.46 %

Importance

Changes 0
Metric Value
dl 14
loc 104
rs 4.7996
c 0
b 0
f 0
cc 18
eloc 55
nc 94
nop 4

How to fix   Long Method    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
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;
13
14
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface;
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifierManagerTrait;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
18
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
19
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
20
use ApiPlatform\Core\Exception\RuntimeException;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use Doctrine\Common\Persistence\ManagerRegistry;
24
use Doctrine\ORM\EntityManagerInterface;
25
use Doctrine\ORM\Mapping\ClassMetadataInfo;
26
27
/**
28
 * Subresource data provider for the Doctrine ORM.
29
 *
30
 * @author Antoine Bluchet <[email protected]>
31
 */
32
final class SubresourceDataProvider implements SubresourceDataProviderInterface
33
{
34
    use IdentifierManagerTrait;
35
36
    private $managerRegistry;
37
    private $collectionExtensions;
38
    private $itemExtensions;
39
40
    /**
41
     * @param ManagerRegistry                        $managerRegistry
42
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
43
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
44
     * @param QueryItemExtensionInterface[]          $itemExtensions
45
     */
46 View Code Duplication
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $collectionExtensions = [], array $itemExtensions = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
47
    {
48
        $this->managerRegistry = $managerRegistry;
49
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
50
        $this->propertyMetadataFactory = $propertyMetadataFactory;
51
        $this->collectionExtensions = $collectionExtensions;
52
        $this->itemExtensions = $itemExtensions;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     *
58
     * @throws RuntimeException
59
     */
60
    public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null)
61
    {
62
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
63
        if (null === $manager) {
64
            throw new ResourceClassNotSupportedException();
65
        }
66
67
        $repository = $manager->getRepository($resourceClass);
68
        if (!method_exists($repository, 'createQueryBuilder')) {
69
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
70
        }
71
72
        if (!isset($context['identifiers']) || !isset($context['property'])) {
73
            throw new ResourceClassNotSupportedException('The given resource class is not a subresource.');
74
        }
75
76
        $queryBuilder = $repository->createQueryBuilder('o');
77
        $queryNameGenerator = new QueryNameGenerator();
78
        $previousQueryBuilder = null;
79
        $previousAlias = null;
80
81
        $num = count($context['identifiers']);
82
83
        while ($num--) {
84
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
85
            $previousIdentifier = $context['identifiers'][$num + 1][0] ?? $context['property'];
86
87
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
88
89
            if (!$manager instanceof EntityManagerInterface) {
90
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
91
            }
92
93
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
94
95
            $qb = $manager->createQueryBuilder();
96
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
97
98
            //MANY_TO_MANY relations needs an explicit join so that the identifier part can be retrieved
99
            if (ClassMetadataInfo::MANY_TO_MANY === $classMetadata->getAssociationMapping($previousIdentifier)['type']) {
100
                $joinAlias = $queryNameGenerator->generateJoinAlias($previousIdentifier);
101
102
                $qb->select($joinAlias)
103
                    ->from($identifierResourceClass, $alias)
104
                    ->innerJoin("$alias.$previousIdentifier", $joinAlias);
105
            } else {
106
                $qb->select("IDENTITY($alias.$previousIdentifier)")
107
                    ->from($identifierResourceClass, $alias);
108
            }
109
110
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
111
112
            foreach ($normalizedIdentifiers as $key => $value) {
113
                $placeholder = $queryNameGenerator->generateParameterName($key);
114
                $qb->andWhere("$alias.$key = :$placeholder");
115
                $queryBuilder->setParameter($placeholder, $value);
116
            }
117
118
            if (null === $previousQueryBuilder) {
119
                $previousQueryBuilder = $qb;
120
            } else {
121
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
122
            }
123
124
            $previousAlias = $alias;
125
        }
126
127
        /*
128
         * The following translate to this pseudo-dql:
129
         *
130
         * SELECT thirdLevel WHERE thirdLevel IN (
131
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
132
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
133
         *   )
134
         * )
135
         *
136
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
137
         */
138
        $queryBuilder->where(
139
            $queryBuilder->expr()->in('o', $previousQueryBuilder->getDQL())
140
        );
141
142
        if (true === $context['collection']) {
143 View Code Duplication
            foreach ($this->collectionExtensions as $extension) {
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...
144
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
145
146
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
147
                    return $extension->getResult($queryBuilder);
148
                }
149
            }
150
        } else {
151 View Code Duplication
            foreach ($this->itemExtensions as $extension) {
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...
152
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
153
154
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
155
                    return $extension->getResult($queryBuilder);
156
                }
157
            }
158
        }
159
160
        $query = $queryBuilder->getQuery();
161
162
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
163
    }
164
}
165