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

SubcollectionDataProvider   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 108
Duplicated Lines 6.48 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
C getSubcollection() 7 81 13

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
38
    /**
39
     * @param ManagerRegistry                        $managerRegistry
40
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
41
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
42
     * @param QueryItemExtensionInterface[]          $itemExtensions
0 ignored issues
show
Bug introduced by
There is no parameter named $itemExtensions. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
43
     */
44
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $collectionExtensions = [])
45
    {
46
        $this->managerRegistry = $managerRegistry;
47
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
48
        $this->propertyMetadataFactory = $propertyMetadataFactory;
49
        $this->collectionExtensions = $collectionExtensions;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     *
55
     * @throws RuntimeException
56
     */
57
    public function getSubcollection(string $resourceClass, array $identifiers, array $context, string $operationName = null)
58
    {
59
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
60
        if (null === $manager) {
61
            throw new ResourceClassNotSupportedException();
62
        }
63
64
        $repository = $manager->getRepository($resourceClass);
65
        if (!method_exists($repository, 'createQueryBuilder')) {
66
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
67
        }
68
69
        if (!isset($context['identifiers']) || !isset($context['property'])) {
70
            throw new ResourceClassNotSupportedException('The given resource class is not a subcollection.');
71
        }
72
73
        $queryBuilder = $repository->createQueryBuilder('o');
74
        $queryNameGenerator = new QueryNameGenerator();
75
        $previousQueryBuilder = null;
76
        $previousAlias = null;
77
78
        $num = count($context['identifiers']);
79
80
        while ($num--) {
81
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
82
            $previousIdentifier = $context['identifiers'][$num + 1][0] ?? $context['property'];
83
84
            $manager = $this->managerRegistry->getManagerForClass($identifierResourceClass);
85
86
            if (!($manager instanceof EntityManagerInterface)) {
87
                throw new RuntimeException("The manager for $identifierResourceClass must be an EntityManager.");
88
            }
89
90
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
91
92
            $qb = $manager->createQueryBuilder();
93
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
94
95
            //MANY_TO_MANY relations needs an explicit join so that the identifier part can be retrieved
96
            if ($classMetadata->getAssociationMapping($previousIdentifier)['type'] === ClassMetadataInfo::MANY_TO_MANY) {
97
                $joinAlias = $queryNameGenerator->generateJoinAlias($previousIdentifier);
98
99
                $qb->select($joinAlias)
100
                    ->from($identifierResourceClass, $alias)
101
                    ->innerJoin("$alias.$previousIdentifier", $joinAlias);
102
            } else {
103
                $qb->select("IDENTITY($alias.$previousIdentifier)")
104
                    ->from($identifierResourceClass, $alias);
105
            }
106
107
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
108
109
            foreach ($normalizedIdentifiers as $key => $value) {
110
                $placeholder = $queryNameGenerator->generateParameterName($key);
111
                $qb->andWhere("$alias.$key = :$placeholder");
112
                $queryBuilder->setParameter($placeholder, $value);
113
            }
114
115
            if (null === $previousQueryBuilder) {
116
                $previousQueryBuilder = $qb;
117
            } else {
118
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
119
            }
120
121
            $previousAlias = $alias;
122
        }
123
124
        $queryBuilder->where(
125
            $queryBuilder->expr()->in('o', $previousQueryBuilder->getDQL())
126
        );
127
128 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...
129
            $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
130
131
            if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
132
                return $extension->getResult($queryBuilder);
133
            }
134
        }
135
136
        return $queryBuilder->getQuery()->getResult();
137
    }
138
}
139