Completed
Pull Request — master (#904)
by Antoine
24:55 queued 19:16
created

SubcollectionDataProvider::getSubcollection()   C

Complexity

Conditions 10
Paths 12

Size

Total Lines 52
Code Lines 30

Duplication

Lines 7
Ratio 13.46 %

Importance

Changes 0
Metric Value
dl 7
loc 52
rs 6.2553
c 0
b 0
f 0
cc 10
eloc 30
nc 12
nop 5

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\Extension\QueryResultExtensionInterface;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifiersHelper;
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 Doctrine\Common\Persistence\ManagerRegistry;
21
use Doctrine\ORM\EntityManagerInterface;
22
23
/**
24
 * Subcollection data provider for the Doctrine ORM.
25
 *
26
 * @author Antoine Bluchet <[email protected]>
27
 */
28
class SubcollectionDataProvider implements SubcollectionDataProviderInterface
29
{
30
    private $managerRegistry;
31
    private $identifiersHelper;
32
    private $collectionExtensions;
33
34
    /**
35
     * @param ManagerRegistry                        $managerRegistry
36
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
0 ignored issues
show
Bug introduced by
There is no parameter named $propertyNameCollectionFactory. 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...
37
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
0 ignored issues
show
Bug introduced by
There is no parameter named $propertyMetadataFactory. 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...
38
     * @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...
39
     */
40
    public function __construct(ManagerRegistry $managerRegistry, IdentifiersHelper $identifiersHelper, array $collectionExtensions = [])
41
    {
42
        $this->managerRegistry = $managerRegistry;
43
        $this->identifiersHelper = $identifiersHelper;
44
        $this->collectionExtensions = $collectionExtensions;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     *
50
     * @throws RuntimeException
51
     */
52
    public function getSubcollection(string $resourceClass, $id, string $subcollectionProperty, string $operationName = null, array $context = [])
53
    {
54
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
55
        if (null === $manager) {
56
            throw new ResourceClassNotSupportedException();
57
        }
58
59
        $identifiers = $this->identifiersHelper->normalizeIdentifiers($id, $manager, $resourceClass);
60
61
        $fetchData = $context['fetch_data'] ?? true;
62
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
63
            return $manager->getReference($resourceClass, $identifiers);
64
        }
65
66
        $classMetadata = $manager->getClassMetadata($resourceClass);
67
        $subResourceClass = $classMetadata->getAssociationTargetClass($subcollectionProperty);
68
        $subResourceClassMetadata = $manager->getClassMetadata($subResourceClass);
69
70
        $repository = $manager->getRepository($subResourceClass);
71
        if (!method_exists($repository, 'createQueryBuilder')) {
72
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
73
        }
74
75
        $queryBuilder = $repository->createQueryBuilder('o');
76
77
        $where = null;
78
        foreach ($identifiers as $identifier => $value) {
79
            $placeholder = ':id_'.$identifier;
80
            $expression = sprintf('parentResourceClass.%s = %s', $identifier, $placeholder);
81
82
            $where = !$where ? $expression : $with.' AND '.$expression;
0 ignored issues
show
Bug introduced by
The variable $with does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
83
            $queryBuilder->setParameter($placeholder, $value);
84
        }
85
86
        //@TODO support composite identifiers relation
87
        $queryBuilder->andWhere(sprintf(
88
            'o.%s IN (SELECT child.%1$s FROM %s parentResourceClass JOIN parentResourceClass.%s child WHERE %s)',
89
            $subResourceClassMetadata->getSingleIdentifierFieldName(), $resourceClass, $subcollectionProperty, $where
90
        ));
91
92
        $queryNameGenerator = new QueryNameGenerator();
93
94 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...
95
            $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
96
97
            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...
98
                return $extension->getResult($queryBuilder);
99
            }
100
        }
101
102
        return $queryBuilder->getQuery()->getResult();
103
    }
104
}
105