Completed
Pull Request — master (#904)
by Antoine
05:04 queued 01:57
created

SubresourceDataProvider::getSubresource()   D

Complexity

Conditions 20
Paths 174

Size

Total Lines 123
Code Lines 68

Duplication

Lines 14
Ratio 11.38 %

Importance

Changes 0
Metric Value
dl 14
loc 123
rs 4.4507
c 0
b 0
f 0
cc 20
eloc 68
nc 174
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
declare(strict_types=1);
4
/*
5
 * This file is part of the API Platform project.
6
 *
7
 * (c) Kévin Dunglas <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;
14
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface;
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifierManagerTrait;
18
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
19
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
20
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
21
use ApiPlatform\Core\Exception\RuntimeException;
22
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
23
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
24
use Doctrine\Common\Persistence\ManagerRegistry;
25
use Doctrine\ORM\EntityManagerInterface;
26
use Doctrine\ORM\Mapping\ClassMetadataInfo;
27
28
/**
29
 * Subresource data provider for the Doctrine ORM.
30
 *
31
 * @author Antoine Bluchet <[email protected]>
32
 */
33
final class SubresourceDataProvider implements SubresourceDataProviderInterface
34
{
35
    use IdentifierManagerTrait;
36
37
    private $managerRegistry;
38
    private $collectionExtensions;
39
    private $itemExtensions;
40
41
    /**
42
     * @param ManagerRegistry                        $managerRegistry
43
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
44
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
45
     * @param QueryItemExtensionInterface[]          $itemExtensions
46
     */
47 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...
48
    {
49
        $this->managerRegistry = $managerRegistry;
50
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
51
        $this->propertyMetadataFactory = $propertyMetadataFactory;
52
        $this->collectionExtensions = $collectionExtensions;
53
        $this->itemExtensions = $itemExtensions;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     *
59
     * @throws RuntimeException
60
     */
61
    public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null)
62
    {
63
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
64
        if (null === $manager) {
65
            throw new ResourceClassNotSupportedException();
66
        }
67
68
        $repository = $manager->getRepository($resourceClass);
69
        if (!method_exists($repository, 'createQueryBuilder')) {
70
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
71
        }
72
73
        if (!isset($context['identifiers']) || !isset($context['property'])) {
74
            throw new ResourceClassNotSupportedException('The given resource class is not a subresource.');
75
        }
76
77
        $originAlias = 'o';
78
        $queryBuilder = $repository->createQueryBuilder($originAlias);
79
        $queryNameGenerator = new QueryNameGenerator();
80
        $previousQueryBuilder = null;
81
        $previousAlias = null;
82
83
        $num = count($context['identifiers']);
84
85
        while ($num--) {
86
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
87
            $previousAssociationProperty = $context['identifiers'][$num + 1][0] ?? $context['property'];
88
89
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
90
91
            if (!$manager instanceof EntityManagerInterface) {
92
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
93
            }
94
95
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
96
97
            $qb = $manager->createQueryBuilder();
98
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
99
            $relationType = $classMetadata->getAssociationMapping($previousAssociationProperty)['type'];
100
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
101
102
            switch ($relationType) {
103
                //MANY_TO_MANY relations need an explicit join so that the identifier part can be retrieved
104
                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...
105
                    $joinAlias = $queryNameGenerator->generateJoinAlias($previousAssociationProperty);
106
107
                    $qb->select($joinAlias)
108
                        ->from($identifierResourceClass, $alias)
109
                        ->innerJoin("$alias.$previousAssociationProperty", $joinAlias);
110
111
                    break;
112
                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...
113
                    $mappedBy = $classMetadata->getAssociationMapping($previousAssociationProperty)['mappedBy'];
114
115
                    // first pass, o.property instead of alias.property
116
                    if (null === $previousQueryBuilder) {
117
                        $originAlias = "$originAlias.$mappedBy";
118
                    } else {
119
                        $previousAlias = "$previousAlias.$mappedBy";
120
                    }
121
122
                    $qb->select($alias)
123
                        ->from($identifierResourceClass, $alias);
124
                    break;
125
                default:
126
                    $qb->select("IDENTITY($alias.$previousAssociationProperty)")
127
                        ->from($identifierResourceClass, $alias);
128
            }
129
130
            // Add where clause for identifiers
131
            foreach ($normalizedIdentifiers as $key => $value) {
132
                $placeholder = $queryNameGenerator->generateParameterName($key);
133
                $qb->andWhere("$alias.$key = :$placeholder");
134
                $queryBuilder->setParameter($placeholder, $value);
135
            }
136
137
            // recurse queries
138
            if (null === $previousQueryBuilder) {
139
                $previousQueryBuilder = $qb;
140
            } else {
141
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
142
            }
143
144
            $previousAlias = $alias;
145
        }
146
147
        /*
148
         * The following translate to this pseudo-dql:
149
         *
150
         * SELECT thirdLevel WHERE thirdLevel IN (
151
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
152
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
153
         *   )
154
         * )
155
         *
156
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
157
         */
158
        $queryBuilder->where(
159
            $queryBuilder->expr()->in($originAlias, $previousQueryBuilder->getDQL())
160
        );
161
162
        if (true === $context['collection']) {
163 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...
164
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
165
166
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
167
                    return $extension->getResult($queryBuilder);
168
                }
169
            }
170
        } else {
171 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...
172
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
173
174
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
175
                    return $extension->getResult($queryBuilder);
176
                }
177
            }
178
        }
179
180
        $query = $queryBuilder->getQuery();
181
182
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
183
    }
184
}
185