Completed
Pull Request — master (#1608)
by Alan
03:37
created

SubresourceDataProvider::getSubresource()   D

Complexity

Conditions 21
Paths 15

Size

Total Lines 127
Code Lines 67

Duplication

Lines 7
Ratio 5.51 %

Importance

Changes 0
Metric Value
dl 7
loc 127
rs 4.6955
c 0
b 0
f 0
cc 21
eloc 67
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
        $buildQuery = function (int $remainingIdentifiers, QueryBuilder $previousQueryBuilder, string $previousAlias, QueryBuilder $topQueryBuilder = null) use (&$buildQuery, $queryNameGenerator, $context, $identifiers): QueryBuilder {
86
            if (!$remainingIdentifiers) {
87
                return $previousQueryBuilder;
88
            }
89
90
            $topQueryBuilder = $topQueryBuilder ?? $previousQueryBuilder;
91
92
            list($identifier, $identifierResourceClass) = $context['identifiers'][$remainingIdentifiers - 1];
93
            $previousAssociationProperty = $context['identifiers'][$remainingIdentifiers][0] ?? $context['property'];
94
95
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
96
97
            if (!$manager instanceof EntityManagerInterface) {
98
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
99
            }
100
101
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
102
103
            if (!$classMetadata instanceof ClassMetadataInfo) {
104
                throw new RuntimeException(
105
                    "The class metadata for $identifierResourceClass must be an instance of ClassMetadataInfo."
106
                );
107
            }
108
109
            $qb = $manager->createQueryBuilder();
110
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
111
            $relationType = $classMetadata->getAssociationMapping($previousAssociationProperty)['type'];
112
            $normalizedIdentifiers = isset($identifiers[$identifier]) ? $this->normalizeIdentifiers(
113
                $identifiers[$identifier],
114
                $manager,
115
                $identifierResourceClass
116
            ) : [];
117
118
            switch ($relationType) {
119
                // MANY_TO_MANY relations need an explicit join so that the identifier part can be retrieved
120
                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...
121
                    $joinAlias = $queryNameGenerator->generateJoinAlias($previousAssociationProperty);
122
123
                    $qb->select($joinAlias)
124
                        ->from($identifierResourceClass, $alias)
125
                        ->innerJoin("$alias.$previousAssociationProperty", $joinAlias);
126
127
                    break;
128
                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...
129
                    $mappedBy = $classMetadata->getAssociationMapping($previousAssociationProperty)['mappedBy'];
130
131
                    $previousAlias = "$previousAlias.$mappedBy";
132
133
                    $qb->select($alias)
134
                        ->from($identifierResourceClass, $alias);
135
                    break;
136
                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...
137
                    $qb->select("IDENTITY($alias.$previousAssociationProperty)")
138
                        ->from($identifierResourceClass, $alias);
139
            }
140
141
            // Add where clause for identifiers
142
            foreach ($normalizedIdentifiers as $key => $value) {
143
                $placeholder = $queryNameGenerator->generateParameterName($key);
144
                $qb->andWhere("$alias.$key = :$placeholder");
145
                $topQueryBuilder->setParameter($placeholder, $value);
146
            }
147
148
            // Recurse queries
149
            $qb = $buildQuery(--$remainingIdentifiers, $qb, $alias, $topQueryBuilder);
150
151
            return $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
152
        };
153
154
        /*
155
         * The following recursively translates to this pseudo-dql:
156
         *
157
         * SELECT thirdLevel WHERE thirdLevel IN (
158
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
159
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
160
         *   )
161
         * )
162
         *
163
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
164
         */
165
        $queryBuilder = $buildQuery(\count($context['identifiers']), $repository->createQueryBuilder($alias = 'o'), $alias);
166
167
        if (true === $context['collection']) {
168
            foreach ($this->collectionExtensions as $extension) {
169
                // We don't need this anymore because we already made sub queries to ensure correct results
170
                if ($extension instanceof FilterEagerLoadingExtension) {
171
                    continue;
172
                }
173
174
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
175
176
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
177
                    return $extension->getResult($queryBuilder, $resourceClass, $operationName);
0 ignored issues
show
Unused Code introduced by
The call to QueryResultCollectionExt...nInterface::getResult() has too many arguments starting with $resourceClass.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
178
                }
179
            }
180
        } else {
181 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...
182
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
183
184
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
185
                    return $extension->getResult($queryBuilder, $resourceClass, $operationName);
0 ignored issues
show
Unused Code introduced by
The call to QueryResultItemExtensionInterface::getResult() has too many arguments starting with $resourceClass.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
186
                }
187
            }
188
        }
189
190
        $query = $queryBuilder->getQuery();
191
192
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
193
    }
194
}
195