Completed
Pull Request — master (#904)
by Antoine
03:22
created

SubresourceDataProvider   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 133
Duplicated Lines 16.54 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 8 8 1
D getSubresource() 14 104 18

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