Completed
Pull Request — 2.0 (#1141)
by Amrouche
03:37
created

SubresourceDataProvider   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 157
Duplicated Lines 14.01 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 14
dl 22
loc 157
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 8 8 1
D getSubresource() 14 127 21

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