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

SubcollectionDataProvider   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 getSubcollection() 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\Util\IdentifierManagerTrait;
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
17
use ApiPlatform\Core\DataProvider\SubcollectionDataProviderInterface;
18
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
19
use ApiPlatform\Core\Exception\RuntimeException;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use Doctrine\Common\Persistence\ManagerRegistry;
23
use Doctrine\ORM\EntityManagerInterface;
24
use Doctrine\ORM\Mapping\ClassMetadataInfo;
25
26
/**
27
 * Subcollection data provider for the Doctrine ORM.
28
 *
29
 * @author Antoine Bluchet <[email protected]>
30
 */
31
class SubcollectionDataProvider implements SubcollectionDataProviderInterface
32
{
33
    use IdentifierManagerTrait;
34
35
    private $managerRegistry;
36
    private $collectionExtensions;
37
    private $itemExtensions;
38
39
    /**
40
     * @param ManagerRegistry                        $managerRegistry
41
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
42
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
43
     * @param QueryItemExtensionInterface[]          $itemExtensions
44
     */
45 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...
46
    {
47
        $this->managerRegistry = $managerRegistry;
48
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
49
        $this->propertyMetadataFactory = $propertyMetadataFactory;
50
        $this->collectionExtensions = $collectionExtensions;
51
        $this->itemExtensions = $itemExtensions;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     *
57
     * @throws RuntimeException
58
     */
59
    public function getSubcollection(string $resourceClass, array $identifiers, array $context, string $operationName = null)
60
    {
61
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
62
        if (null === $manager) {
63
            throw new ResourceClassNotSupportedException();
64
        }
65
66
        $repository = $manager->getRepository($resourceClass);
67
        if (!method_exists($repository, 'createQueryBuilder')) {
68
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
69
        }
70
71
        if (!isset($context['identifiers']) || !isset($context['property'])) {
72
            throw new ResourceClassNotSupportedException('The given resource class is not a subcollection.');
73
        }
74
75
        $queryBuilder = $repository->createQueryBuilder('o');
76
        $queryNameGenerator = new QueryNameGenerator();
77
        $previousQueryBuilder = null;
78
        $previousAlias = null;
79
80
        $num = count($context['identifiers']);
81
82
        while ($num--) {
83
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
84
            $previousIdentifier = $context['identifiers'][$num + 1][0] ?? $context['property'];
85
86
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
87
88
            if (!$manager instanceof EntityManagerInterface) {
89
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
90
            }
91
92
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
93
94
            $qb = $manager->createQueryBuilder();
95
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
96
97
            //MANY_TO_MANY relations needs an explicit join so that the identifier part can be retrieved
98
            if ($classMetadata->getAssociationMapping($previousIdentifier)['type'] === ClassMetadataInfo::MANY_TO_MANY) {
99
                $joinAlias = $queryNameGenerator->generateJoinAlias($previousIdentifier);
100
101
                $qb->select($joinAlias)
102
                    ->from($identifierResourceClass, $alias)
103
                    ->innerJoin("$alias.$previousIdentifier", $joinAlias);
104
            } else {
105
                $qb->select("IDENTITY($alias.$previousIdentifier)")
106
                    ->from($identifierResourceClass, $alias);
107
            }
108
109
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
110
111
            foreach ($normalizedIdentifiers as $key => $value) {
112
                $placeholder = $queryNameGenerator->generateParameterName($key);
113
                $qb->andWhere("$alias.$key = :$placeholder");
114
                $queryBuilder->setParameter($placeholder, $value);
115
            }
116
117
            if (null === $previousQueryBuilder) {
118
                $previousQueryBuilder = $qb;
119
            } else {
120
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
121
            }
122
123
            $previousAlias = $alias;
124
        }
125
126
        /*
127
         * The following translate to this pseudo-dql:
128
         *
129
         * SELECT thirdLevel WHERE thirdLevel IN (
130
         *   SELECT thirdLevel FROM relatedDummies WHERE relatedDummies = ? AND relatedDummies IN (
131
         *     SELECT relatedDummies FROM Dummy WHERE Dummy = ?
132
         *   )
133
         * )
134
         *
135
         * By using subqueries, we're forcing the SQL execution plan to go through indexes on doctrine identifiers.
136
         */
137
        $queryBuilder->where(
138
            $queryBuilder->expr()->in('o', $previousQueryBuilder->getDQL())
139
        );
140
141
        if (true === $context['collection']) {
142 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...
143
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
144
145
                if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
146
                    return $extension->getResult($queryBuilder);
147
                }
148
            }
149
        } else {
150 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...
151
                $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
152
153
                if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
0 ignored issues
show
Bug introduced by
The class ApiPlatform\Core\Bridge\...tItemExtensionInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
154
                    return $extension->getResult($queryBuilder);
155
                }
156
            }
157
        }
158
159
        $query = $queryBuilder->getQuery();
160
161
        return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
162
    }
163
}
164