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

SubcollectionDataProvider::getSubcollection()   C

Complexity

Conditions 11
Paths 41

Size

Total Lines 74
Code Lines 44

Duplication

Lines 7
Ratio 9.46 %

Importance

Changes 0
Metric Value
dl 7
loc 74
rs 5.5364
c 0
b 0
f 0
cc 11
eloc 44
nc 41
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Util\QueryNameGenerator;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifierManagerTrait;
16
use ApiPlatform\Core\DataProvider\SubcollectionDataProviderInterface;
17
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
18
use ApiPlatform\Core\Exception\RuntimeException;
19
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
21
use Doctrine\Common\Persistence\ManagerRegistry;
22
use Doctrine\ORM\EntityManagerInterface;
23
use Doctrine\ORM\Mapping\ClassMetadataInfo;
24
25
/**
26
 * Subcollection data provider for the Doctrine ORM.
27
 *
28
 * @author Antoine Bluchet <[email protected]>
29
 */
30
class SubcollectionDataProvider implements SubcollectionDataProviderInterface
31
{
32
    use IdentifierManagerTrait;
33
34
    private $managerRegistry;
35
    private $collectionExtensions;
36
37
    /**
38
     * @param ManagerRegistry                        $managerRegistry
39
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
40
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
41
     * @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...
42
     */
43
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $collectionExtensions = [])
44
    {
45
        $this->managerRegistry = $managerRegistry;
46
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
47
        $this->propertyMetadataFactory = $propertyMetadataFactory;
48
        $this->collectionExtensions = $collectionExtensions;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     *
54
     * @throws RuntimeException
55
     */
56
    public function getSubcollection(string $resourceClass, array $identifiers, array $context = [], string $operationName)
57
    {
58
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
59
        if (null === $manager) {
60
            throw new ResourceClassNotSupportedException();
61
        }
62
63
        $repository = $manager->getRepository($resourceClass);
64
        if (!method_exists($repository, 'createQueryBuilder')) {
65
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
66
        }
67
68
        $queryBuilder = $repository->createQueryBuilder('o');
69
        $queryNameGenerator = new QueryNameGenerator();
70
        $previousQueryBuilder = null;
71
        $previousAlias = null;
72
73
        $num = count($context['identifiers']);
74
75
        while ($num--) {
76
            list($identifier, $identifierResourceClass) = $context['identifiers'][$num];
77
            $previousIdentifier = $context['identifiers'][$num + 1][0] ?? $context['property'];
78
79
            $classMetadata = $manager->getClassMetadata($identifierResourceClass);
80
81
            $qb = $manager->createQueryBuilder();
82
            $alias = $queryNameGenerator->generateJoinAlias($identifier);
83
84
            if (null !== $previousIdentifier) {
85
                //MANY_TO_MANY relations needs an explicit join so that the identifier part can be retrieved
86
                if ($classMetadata->getAssociationMapping($previousIdentifier)['type'] === ClassMetadataInfo::MANY_TO_MANY) {
87
                    $joinAlias = $queryNameGenerator->generateJoinAlias($previousIdentifier);
88
89
                    $qb->select($joinAlias)
90
                        ->from($identifierResourceClass, $alias)
91
                        ->innerJoin("$alias.$previousIdentifier", $joinAlias);
92
93
                } else {
94
                    $qb->select("IDENTITY($alias.$previousIdentifier)")
95
                        ->from($identifierResourceClass, $alias);
96
                }
97
            }
98
99
            $normalizedIdentifiers = $this->normalizeIdentifiers($identifiers[$identifier], $manager, $identifierResourceClass);
100
101
            foreach ($normalizedIdentifiers as $key => $value) {
102
                $placeholder = $queryNameGenerator->generateParameterName($key);
103
                $qb->andWhere("$alias.$key = :$placeholder");
104
                $queryBuilder->setParameter($placeholder, $value);
105
            }
106
107
            if (null === $previousQueryBuilder) {
108
                $previousQueryBuilder = $qb;
109
            } else {
110
                $previousQueryBuilder->andWhere($qb->expr()->in($previousAlias, $qb->getDQL()));
111
            }
112
113
            $previousAlias = $alias;
114
        }
115
116
        $queryBuilder->where(
117
            $queryBuilder->expr()->in('o', $previousQueryBuilder->getDQL())
118
        );
119
120 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...
121
			$extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
122
123
			if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
0 ignored issues
show
Bug introduced by
The class ApiPlatform\Core\Bridge\...ctionExtensionInterface 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...
124
				return $extension->getResult($queryBuilder);
125
			}
126
		}
127
128
        return $queryBuilder->getQuery()->getResult();
129
    }
130
}
131