Completed
Pull Request — master (#1245)
by Antoine
03:06
created

SubresourceDataProvider::getSubresource()   F

Complexity

Conditions 23
Paths 401

Size

Total Lines 132
Code Lines 72

Duplication

Lines 7
Ratio 5.3 %

Importance

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

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
174
                    continue;
175
                }
176
177
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
178
179
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
180
                    return $extension->getResult($queryBuilder);
181
                }
182
            }
183
        } else {
184 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...
185
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
186
187
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
188
                    return $extension->getResult($queryBuilder);
189
                }
190
            }
191
        }
192
193
        $query = $queryBuilder->getQuery();
194
195
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
196
    }
197
}
198