Completed
Push — master ( 131c91...75b368 )
by Kévin
03:30
created

SubresourceDataProvider   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 162
Duplicated Lines 9.26 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 14
dl 15
loc 162
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 8 8 1
F getSubresource() 7 132 23

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
32
/**
33
 * Subresource data provider for the Doctrine ORM.
34
 *
35
 * @author Antoine Bluchet <[email protected]>
36
 */
37
final class SubresourceDataProvider implements SubresourceDataProviderInterface
38
{
39
    use IdentifierManagerTrait;
40
41
    private $managerRegistry;
42
    private $collectionExtensions;
43
    private $itemExtensions;
44
45
    /**
46
     * @param ManagerRegistry                        $managerRegistry
47
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
48
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
49
     * @param QueryCollectionExtensionInterface[]    $collectionExtensions
50
     * @param QueryItemExtensionInterface[]          $itemExtensions
51
     */
52 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...
53
    {
54
        $this->managerRegistry = $managerRegistry;
55
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
56
        $this->propertyMetadataFactory = $propertyMetadataFactory;
57
        $this->collectionExtensions = $collectionExtensions;
58
        $this->itemExtensions = $itemExtensions;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     *
64
     * @throws RuntimeException
65
     */
66
    public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null)
67
    {
68
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
69
        if (null === $manager) {
70
            throw new ResourceClassNotSupportedException();
71
        }
72
73
        $repository = $manager->getRepository($resourceClass);
74
        if (!method_exists($repository, 'createQueryBuilder')) {
75
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
76
        }
77
78
        if (!isset($context['identifiers']) || !isset($context['property'])) {
79
            throw new ResourceClassNotSupportedException('The given resource class is not a subresource.');
80
        }
81
82
        $originAlias = 'o';
83
        $queryBuilder = $repository->createQueryBuilder($originAlias);
84
        $queryNameGenerator = new QueryNameGenerator();
85
        $previousQueryBuilder = null;
86
        $previousAlias = null;
87
88
        $num = count($context['identifiers']);
89
90
        while ($num--) {
91
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
92
            $previousAssociationProperty = $context['identifiers'][$num + 1][0] ?? $context['property'];
93
94
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
95
96
            if (!$manager instanceof EntityManagerInterface) {
97
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
98
            }
99
100
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
101
102
            if (!$classMetadata instanceof ClassMetadataInfo) {
103
                throw new RuntimeException("The class metadata for $identifierResourceClass must be an instance of ClassMetadataInfo.");
104
            }
105
106
            $qb = $manager->createQueryBuilder();
107
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
108
            $relationType = $classMetadata->getAssociationMapping($previousAssociationProperty)['type'];
109
            $normalizedIdentifiers = isset($identifiers[$identifier]) ? $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass) : [];
110
111
            switch ($relationType) {
112
                //MANY_TO_MANY relations need an explicit join so that the identifier part can be retrieved
113
                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...
114
                    $joinAlias = $queryNameGenerator->generateJoinAlias($previousAssociationProperty);
115
116
                    $qb->select($joinAlias)
117
                        ->from($identifierResourceClass, $alias)
118
                        ->innerJoin("$alias.$previousAssociationProperty", $joinAlias);
119
120
                    break;
121
                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...
122
                    $mappedBy = $classMetadata->getAssociationMapping($previousAssociationProperty)['mappedBy'];
123
124
                    // first pass, o.property instead of alias.property
125
                    if (null === $previousQueryBuilder) {
126
                        $originAlias = "$originAlias.$mappedBy";
127
                    } else {
128
                        $previousAlias = "$previousAlias.$mappedBy";
129
                    }
130
131
                    $qb->select($alias)
132
                        ->from($identifierResourceClass, $alias);
133
                    break;
134
                default:
135
                    $qb->select("IDENTITY($alias.$previousAssociationProperty)")
136
                        ->from($identifierResourceClass, $alias);
137
            }
138
139
            // Add where clause for identifiers
140
            foreach ($normalizedIdentifiers as $key => $value) {
141
                $placeholder = $queryNameGenerator->generateParameterName($key);
142
                $qb->andWhere("$alias.$key = :$placeholder");
143
                $queryBuilder->setParameter($placeholder, $value);
144
            }
145
146
            // recurse queries
147
            if (null === $previousQueryBuilder) {
148
                $previousQueryBuilder = $qb;
149
            } else {
150
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
151
            }
152
153
            $previousAlias = $alias;
154
        }
155
156
        /*
157
         * The following translate to this pseudo-dql:
158
         *
159
         * SELECT thirdLevel WHERE thirdLevel IN (
160
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
161
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
162
         *   )
163
         * )
164
         *
165
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
166
         */
167
        $queryBuilder->where(
168
            $queryBuilder->expr()->in($originAlias, $previousQueryBuilder->getDQL())
169
        );
170
171
        if (true === $context['collection']) {
172
            foreach ($this->collectionExtensions as $extension) {
173
                // We don't need this anymore because we already made sub queries to ensure correct results
174
                if ($extension instanceof FilterEagerLoadingExtension) {
175
                    continue;
176
                }
177
178
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
179
180
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
181
                    return $extension->getResult($queryBuilder);
182
                }
183
            }
184
        } else {
185 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...
186
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
187
188
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
189
                    return $extension->getResult($queryBuilder);
190
                }
191
            }
192
        }
193
194
        $query = $queryBuilder->getQuery();
195
196
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
197
    }
198
}
199