Completed
Push — 2.1 ( 3d4fea...a62e08 )
by Kévin
13:01
created

SubresourceDataProvider::getSubresource()   C

Complexity

Conditions 14
Paths 15

Size

Total Lines 58
Code Lines 25

Duplication

Lines 7
Ratio 12.07 %

Importance

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

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
166
                $joinAlias = $queryNameGenerator->generateJoinAlias($previousAssociationProperty);
167
168
                $qb->select($joinAlias)
169
                    ->from($identifierResourceClass, $alias)
170
                    ->innerJoin("$alias.$previousAssociationProperty", $joinAlias);
171
                break;
172
            case ClassMetadataInfo::ONE_TO_MANY:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
173
                $mappedBy = $classMetadata->getAssociationMapping($previousAssociationProperty)['mappedBy'];
174
                $previousAlias = "$previousAlias.$mappedBy";
175
176
                $qb->select($alias)
177
                    ->from($identifierResourceClass, $alias);
178
                break;
179
            default:
0 ignored issues
show
Coding Style introduced by
DEFAULT statements must be defined using a colon

As per the PSR-2 coding standard, default statements should not be wrapped in curly braces.

switch ($expr) {
    default: { //wrong
        doSomething();
        break;
    }
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
180
                $qb->select("IDENTITY($alias.$previousAssociationProperty)")
181
                    ->from($identifierResourceClass, $alias);
182
        }
183
184
        // Add where clause for identifiers
185
        foreach ($normalizedIdentifiers as $key => $value) {
186
            $placeholder = $queryNameGenerator->generateParameterName($key);
187
            $qb->andWhere("$alias.$key = :$placeholder");
188
            $topQueryBuilder->setParameter($placeholder, $value);
189
        }
190
191
        // Recurse queries
192
        $qb = $this->buildQuery($identifiers, $context, $queryNameGenerator, $qb, $alias, --$remainingIdentifiers, $topQueryBuilder);
193
194
        return $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
195
    }
196
}
197