Completed
Push — 2.0 ( 730599...4e1b10 )
by Amrouche
18s
created

ItemDataProvider   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 88
Duplicated Lines 7.95 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
D getItem() 7 38 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\Exception\InvalidArgumentException;
22
use ApiPlatform\Core\Exception\PropertyNotFoundException;
23
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
24
use ApiPlatform\Core\Exception\RuntimeException;
25
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
26
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
27
use Doctrine\Common\Persistence\ManagerRegistry;
28
use Doctrine\ORM\EntityManagerInterface;
29
use Doctrine\ORM\QueryBuilder;
30
31
/**
32
 * Item data provider for the Doctrine ORM.
33
 *
34
 * @author Kévin Dunglas <[email protected]>
35
 * @author Samuel ROZE <[email protected]>
36
 */
37
class ItemDataProvider implements ItemDataProviderInterface
38
{
39
    use IdentifierManagerTrait;
40
41
    private $managerRegistry;
42
    private $itemExtensions;
43
44
    /**
45
     * @param ManagerRegistry                        $managerRegistry
46
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
47
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
48
     * @param QueryItemExtensionInterface[]          $itemExtensions
49
     */
50
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [])
51
    {
52
        $this->managerRegistry = $managerRegistry;
53
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
54
        $this->propertyMetadataFactory = $propertyMetadataFactory;
55
        $this->itemExtensions = $itemExtensions;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     *
61
     * The context may contain a `fetch_data` key representing whether the value should be fetched by Doctrine or if we should return a reference.
62
     *
63
     * @throws RuntimeException
64
     */
65
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = [])
66
    {
67
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
68
        if (null === $manager) {
69
            throw new ResourceClassNotSupportedException();
70
        }
71
72
        try {
73
            $identifiers = $this->normalizeIdentifiers($id, $manager, $resourceClass);
74
        } catch (PropertyNotFoundException $e) {
75
            throw new InvalidArgumentException($e->getMessage());
76
        }
77
78
        $fetchData = $context['fetch_data'] ?? true;
79
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
80
            return $manager->getReference($resourceClass, $identifiers);
81
        }
82
83
        $repository = $manager->getRepository($resourceClass);
84
        if (!method_exists($repository, 'createQueryBuilder')) {
85
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
86
        }
87
88
        $queryBuilder = $repository->createQueryBuilder('o');
89
        $queryNameGenerator = new QueryNameGenerator();
90
91
        $this->addWhereForIdentifiers($identifiers, $queryBuilder);
92
93 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...
94
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
95
96
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
97
                return $extension->getResult($queryBuilder);
98
            }
99
        }
100
101
        return $queryBuilder->getQuery()->getOneOrNullResult();
102
    }
103
104
    /**
105
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
106
     *
107
     * @param array        $identifiers
108
     * @param QueryBuilder $queryBuilder
109
     */
110
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder)
111
    {
112
        foreach ($identifiers as $identifier => $value) {
113
            $placeholder = ':id_'.$identifier;
114
            $expression = $queryBuilder->expr()->eq(
115
                'o.'.$identifier,
116
                $placeholder
117
            );
118
119
            $queryBuilder->andWhere($expression);
120
121
            $queryBuilder->setParameter($placeholder, $value);
122
        }
123
    }
124
}
125