Completed
Pull Request — master (#904)
by Antoine
02:47
created

SubresourceDataProvider::getSubresource()   D

Complexity

Conditions 20
Paths 174

Size

Total Lines 124
Code Lines 68

Duplication

Lines 14
Ratio 11.29 %

Importance

Changes 0
Metric Value
dl 14
loc 124
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
/*
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
        $originAlias = 'o';
77
        $queryBuilder = $repository->createQueryBuilder($originAlias);
78
        $queryNameGenerator = new QueryNameGenerator();
79
        $previousQueryBuilder = null;
80
        $previousAlias = null;
81
82
        $num = count($context['identifiers']);
83
84
        while ($num--) {
85
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
86
            $previousAssociationProperty = $context['identifiers'][$num + 1][0] ?? $context['property'];
87
88
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
89
90
            if (!$manager instanceof EntityManagerInterface) {
91
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
92
            }
93
94
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
95
96
            $qb = $manager->createQueryBuilder();
97
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
98
            $relationType = $classMetadata->getAssociationMapping($previousAssociationProperty)['type'];
99
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
100
101
            switch ($relationType) {
102
                //MANY_TO_MANY relations need an explicit join so that the identifier part can be retrieved
103
                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...
104
                    $joinAlias = $queryNameGenerator->generateJoinAlias($previousAssociationProperty);
105
106
                    $qb->select($joinAlias)
107
                        ->from($identifierResourceClass, $alias)
108
                        ->innerJoin("$alias.$previousAssociationProperty", $joinAlias);
109
110
                    break;
111
                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...
112
                    $mappedBy = $classMetadata->getAssociationMapping($previousAssociationProperty)['mappedBy'];
113
114
                    // first pass, o.property instead of alias.property
115
                    if (null === $previousQueryBuilder) {
116
                        $originAlias = "$originAlias.$mappedBy";
117
                    } else {
118
                        $previousAlias = "$previousAlias.$mappedBy";
119
                    }
120
121
                    $qb->select($alias)
122
                        ->from($identifierResourceClass, $alias);
123
                    break;
124
                default:
125
                    $qb->select("IDENTITY($alias.$previousAssociationProperty)")
126
                        ->from($identifierResourceClass, $alias);
127
            }
128
129
            // Add where clause for identifiers
130
            foreach ($normalizedIdentifiers as $key => $value) {
131
                $placeholder = $queryNameGenerator->generateParameterName($key);
132
                $qb->andWhere("$alias.$key = :$placeholder");
133
                $queryBuilder->setParameter($placeholder, $value);
134
            }
135
136
            // recurse queries
137
            if (null === $previousQueryBuilder) {
138
                $previousQueryBuilder = $qb;
139
            } else {
140
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
141
            }
142
143
            $previousAlias = $alias;
144
        }
145
146
        /*
147
         * The following translate to this pseudo-dql:
148
         *
149
         * SELECT thirdLevel WHERE thirdLevel IN (
150
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
151
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
152
         *   )
153
         * )
154
         *
155
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
156
         */
157
        $queryBuilder->where(
158
            $queryBuilder->expr()->in($originAlias, $previousQueryBuilder->getDQL())
159
        );
160
161
        if (true === $context['collection']) {
162 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...
163
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
164
165
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
166
                    return $extension->getResult($queryBuilder);
167
                }
168
            }
169
        } else {
170 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...
171
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
172
173
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
174
                    return $extension->getResult($queryBuilder);
175
                }
176
            }
177
        }
178
179
180
        $query = $queryBuilder->getQuery();
181
182
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
183
    }
184
}
185