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

ItemDataProvider   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 95
Duplicated Lines 7.37 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A supports() 0 4 1
D getItem() 7 39 9
A addWhereForIdentifiers() 0 14 2

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
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface;
18
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifierManagerTrait;
19
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
20
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
21
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
22
use ApiPlatform\Core\Exception\RuntimeException;
23
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use Doctrine\Common\Persistence\ManagerRegistry;
26
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
27
use Doctrine\ORM\EntityManagerInterface;
28
use Doctrine\ORM\QueryBuilder;
29
30
/**
31
 * Item data provider for the Doctrine ORM.
32
 *
33
 * @author Kévin Dunglas <[email protected]>
34
 * @author Samuel ROZE <[email protected]>
35
 */
36
class ItemDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
37
{
38
    use IdentifierManagerTrait;
39
40
    private $managerRegistry;
41
    private $itemExtensions;
42
43
    /**
44
     * @param ManagerRegistry                        $managerRegistry
45
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
46
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
47
     * @param QueryItemExtensionInterface[]          $itemExtensions
48
     */
49
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [])
50
    {
51
        $this->managerRegistry = $managerRegistry;
52
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
53
        $this->propertyMetadataFactory = $propertyMetadataFactory;
54
        $this->itemExtensions = $itemExtensions;
55
    }
56
57
    public function supports(string $resourceClass, string $operationName = null): bool
58
    {
59
        return null !== $this->managerRegistry->getManagerForClass($resourceClass);
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     *
65
     * The context may contain a `fetch_data` key representing whether the value should be fetched by Doctrine or if we should return a reference.
66
     *
67
     * @throws RuntimeException
68
     */
69
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []/**, array $identifiers = []**/)
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
70
    {
71
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
72
73
        $identifiers = null;
74
        if (5 === func_num_args()) {
75
            $identifiers = func_get_arg(4);
76
        }
77
78
        if (!$identifiers) {
79
            $identifiers = $this->normalizeIdentifiers($id, $manager, $resourceClass);
0 ignored issues
show
Bug introduced by
It seems like $manager defined by $this->managerRegistry->...orClass($resourceClass) on line 71 can be null; however, ApiPlatform\Core\Bridge\...:normalizeIdentifiers() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
80
        }
81
82
        $fetchData = $context['fetch_data'] ?? true;
83
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
84
            return $manager->getReference($resourceClass, $identifiers);
85
        }
86
87
        $repository = $manager->getRepository($resourceClass);
88
        if (!method_exists($repository, 'createQueryBuilder')) {
89
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
90
        }
91
92
        $queryBuilder = $repository->createQueryBuilder('o');
93
        $queryNameGenerator = new QueryNameGenerator();
94
        $doctrineClassMetadata = $manager->getClassMetadata($resourceClass);
95
96
        $this->addWhereForIdentifiers($identifiers, $queryBuilder, $doctrineClassMetadata);
97
98 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...
99
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
100
101
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
102
                return $extension->getResult($queryBuilder);
103
            }
104
        }
105
106
        return $queryBuilder->getQuery()->getOneOrNullResult();
107
    }
108
109
    /**
110
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
111
     *
112
     * @param array         $identifiers
113
     * @param QueryBuilder  $queryBuilder
114
     * @param ClassMetadata $classMetadata
115
     */
116
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder, ClassMetadata $classMetadata)
117
    {
118
        foreach ($identifiers as $identifier => $value) {
119
            $placeholder = ':id_'.$identifier;
120
            $expression = $queryBuilder->expr()->eq(
121
                'o.'.$identifier,
122
                $placeholder
123
            );
124
125
            $queryBuilder->andWhere($expression);
126
127
            $queryBuilder->setParameter($placeholder, $value, $classMetadata->getTypeOfField($identifier));
128
        }
129
    }
130
}
131