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

SubresourceDataProvider   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 146
Duplicated Lines 15.07 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 8 8 1
D getSubresource() 14 117 20

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
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
            $previousIdentifier = $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
99
            $relationType = $classMetadata->getAssociationMapping($previousIdentifier)['type'];
100
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
101
102
            //MANY_TO_MANY relations needs an explicit join so that the identifier part can be retrieved
103
            if (ClassMetadataInfo::MANY_TO_MANY === $relationType) {
104
                $joinAlias = $queryNameGenerator->generateJoinAlias($previousIdentifier);
105
106
                $qb->select($joinAlias)
107
                    ->from($identifierResourceClass, $alias)
108
                    ->innerJoin("$alias.$previousIdentifier", $joinAlias);
109
            } elseif (ClassMetadataInfo::ONE_TO_MANY === $relationType) {
110
                $mappedBy = $classMetadata->getAssociationMapping($previousIdentifier)['mappedBy'];
111
112
                if (null === $previousQueryBuilder) {
113
                    $originAlias = "$originAlias.$mappedBy";
114
                } else {
115
                    $previousAlias = "$previousAlias.$mappedBy";
116
                }
117
118
                $qb->select($alias)
119
                    ->from($identifierResourceClass, $alias);
120
            } else {
121
                $qb->select("IDENTITY($alias.$previousIdentifier)")
122
                    ->from($identifierResourceClass, $alias);
123
            }
124
125
            foreach ($normalizedIdentifiers as $key => $value) {
126
                $placeholder = $queryNameGenerator->generateParameterName($key);
127
                $qb->andWhere("$alias.$key = :$placeholder");
128
                $queryBuilder->setParameter($placeholder, $value);
129
            }
130
131
            if (null === $previousQueryBuilder) {
132
                $previousQueryBuilder = $qb;
133
            } else {
134
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
135
            }
136
137
            $previousAlias = $alias;
138
        }
139
140
        /*
141
         * The following translate to this pseudo-dql:
142
         *
143
         * SELECT thirdLevel WHERE thirdLevel IN (
144
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
145
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
146
         *   )
147
         * )
148
         *
149
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
150
         */
151
        $queryBuilder->where(
152
            $queryBuilder->expr()->in($originAlias, $previousQueryBuilder->getDQL())
153
        );
154
155
        if (true === $context['collection']) {
156 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...
157
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
158
159
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
160
                    return $extension->getResult($queryBuilder);
161
                }
162
            }
163
        } else {
164 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...
165
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
166
167
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
168
                    return $extension->getResult($queryBuilder);
169
                }
170
            }
171
        }
172
173
        $query = $queryBuilder->getQuery();
174
175
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
176
    }
177
}
178