Completed
Pull Request — master (#458)
by Théo
05:10 queued 02:09
created

ItemDataProvider   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 168
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 4
Bugs 2 Features 0
Metric Value
wmc 22
c 4
b 2
f 0
lcom 1
cbo 15
dl 0
loc 168
rs 9.1666

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A getItem() 0 12 3
A fallbackGetItem() 0 18 4
A getManagerForClass() 0 9 2
B getIdentifiers() 0 24 5
B retrieveQueryBuilder() 0 33 5
A applyIdentifiersToQueryBuilder() 0 10 2
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\Api\ItemDataProviderInterface;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
16
use ApiPlatform\Core\Exception\InvalidArgumentException;
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\Common\Persistence\ObjectManager;
23
use Doctrine\ORM\EntityManagerInterface;
24
use Doctrine\ORM\EntityRepository;
25
use Doctrine\ORM\QueryBuilder;
26
27
/**
28
 * Item data provider for the Doctrine ORM.
29
 *
30
 * @author Kévin Dunglas <[email protected]>
31
 * @author Samuel ROZE <[email protected]>
32
 * @author Théo FIDRY <[email protected]>
33
 */
34
class ItemDataProvider implements ItemDataProviderInterface
35
{
36
    private $managerRegistry;
37
    private $propertyNameCollectionFactory;
38
    private $propertyMetadataFactory;
39
    private $itemExtensions;
40
    private $decoratedProvider;
41
42
    /**
43
     * @param ManagerRegistry                        $managerRegistry
44
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
45
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
46
     * @param QueryItemExtensionInterface[]          $itemExtensions
47
     * @param ItemDataProviderInterface|null         $decoratedProvider
48
     */
49
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [], ItemDataProviderInterface $decoratedProvider = null)
50
    {
51
        $this->managerRegistry = $managerRegistry;
52
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
53
        $this->propertyMetadataFactory = $propertyMetadataFactory;
54
        $this->itemExtensions = $itemExtensions;
55
        $this->decoratedProvider = $decoratedProvider;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function getItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
62
    {
63
        if (null !== $this->decoratedProvider) {
64
            try {
65
                return $this->decoratedProvider->getItem($resourceClass, $id, $operationName, $fetchData);
66
            } catch (ResourceClassNotSupportedException $resourceClassNotSupportedException) {
67
                // Ignore it
68
            }
69
        }
70
71
        return $this->fallbackGetItem($resourceClass, $id, $operationName, $fetchData);
72
    }
73
74
    /**
75
     * @param string      $resourceClass
76
     * @param int|string  $id
77
     * @param string|null $operationName
78
     * @param bool        $fetchData
79
     *
80
     * @return object
81
     * @throws ResourceClassNotSupportedException
82
     */
83
    private function fallbackGetItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
84
    {
85
        $manager = $this->getManagerForClass($resourceClass);
86
        $identifiers = $this->getIdentifiers($resourceClass, $id);
87
88
        if (!$fetchData || $manager instanceof EntityManagerInterface) {
89
            return $manager->getReference($resourceClass, $identifiers);
90
        }
91
92
        $queryBuilder = $this->retrieveQueryBuilder($manager, $resourceClass);
93
        $this->applyIdentifiersToQueryBuilder($queryBuilder, $identifiers);
94
95
        foreach ($this->itemExtensions as $extension) {
96
            $extension->applyToItem($queryBuilder, $resourceClass, $identifiers, $operationName);
97
        }
98
99
        return $queryBuilder->getQuery()->getOneOrNullResult();
100
    }
101
102
    /**
103
     * @param string $resourceClass
104
     *
105
     * @return ObjectManager
106
     * @throws ResourceClassNotSupportedException
107
     */
108
    private function getManagerForClass(string $resourceClass)
109
    {
110
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
111
        if (null !== $manager) {
112
            return $manager;
113
        }
114
115
        throw new ResourceClassNotSupportedException();
116
    }
117
118
    /**
119
     * @param string     $resourceClass
120
     * @param int|string $id
121
     *
122
     * @return array Identifier values with keys as property names
123
     */
124
    private function getIdentifiers(string $resourceClass, $id)
125
    {
126
        $identifierValues = explode('-', $id);
127
        $identifiers = [];
128
        $i = 0;
129
130
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
131
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
132
133
            $identifier = $propertyMetadata->isIdentifier();
134
            if (null === $identifier || false === $identifier) {
135
                continue;
136
            }
137
138
            if (!isset($identifierValues[$i])) {
139
                throw new InvalidArgumentException(sprintf('Invalid identifier "%s".', $id));
140
            }
141
142
            $identifiers[$propertyName] = $identifierValues[$i];
143
            ++$i;
144
        }
145
146
        return $identifiers;
147
    }
148
149
    /**
150
     * @param ObjectManager $resourceManager
151
     * @param string        $resourceClass
152
     *
153
     * @throws RuntimeException
154
     *
155
     * @return \Doctrine\ORM\QueryBuilder
156
     */
157
    private function retrieveQueryBuilder(ObjectManager $resourceManager, string $resourceClass)
158
    {
159
        $repository = $resourceManager->getRepository($resourceClass);
160
161
        if ($repository instanceof EntityRepository) {
162
            return $repository->createQueryBuilder('o');
163
        }
164
165
        if ($resourceManager instanceof EntityManagerInterface) {
166
            return $resourceManager->createQueryBuilder()
167
                ->select('o')
168
                ->from($resourceClass, 'o');
169
        }
170
171
        if (method_exists($repository, 'createQueryBuilder')) {
172
            return $repository->createQueryBuilder('o');
173
        }
174
175
        if (method_exists($resourceManager, 'createQueryBuilder')) {
176
            return $resourceManager->createQueryBuilder()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method createQueryBuilder() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
177
                ->select('o')
178
                ->from($resourceClass, 'o');
179
        }
180
181
        throw new RuntimeException(
182
            sprintf(
183
                'The object manager "%s" or resource manager "%s" of the resource "%s" must have a ::createQueryBuilder() method.',
184
                get_class($resourceManager),
185
                get_class($repository),
186
                $resourceClass
187
            )
188
        );
189
    }
190
191
    private function applyIdentifiersToQueryBuilder(QueryBuilder $queryBuilder, array $identifiers)
192
    {
193
        foreach ($identifiers as $propertyName => $value) {
194
            $placeholder = 'id_'.$propertyName;
195
196
            $queryBuilder
197
                ->where($queryBuilder->expr()->eq('o.'.$propertyName, ':'.$placeholder))
198
                ->setParameter($placeholder, $value);
199
        }
200
    }
201
}
202