Completed
Pull Request — master (#458)
by Théo
03:08
created

ItemDataProvider::retrieveQueryBuilder()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 33
rs 8.439
cc 5
eloc 20
nc 5
nop 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
     * @return \Doctrine\ORM\QueryBuilder
154
     */
155
    private function retrieveQueryBuilder(ObjectManager $resourceManager, string $resourceClass)
156
    {
157
        $repository = $resourceManager->getRepository($resourceClass);
158
159
        if ($repository instanceof EntityRepository) {
160
            return $repository->createQueryBuilder('o');
161
        }
162
163
        if ($resourceManager instanceof EntityManagerInterface) {
164
            return $resourceManager->createQueryBuilder()
165
                ->select('o')
166
                ->from($resourceClass, 'o');
167
        }
168
169
        if (method_exists($repository, 'createQueryBuilder')) {
170
            return $repository->createQueryBuilder('o');
171
        }
172
173
        if (method_exists($resourceManager, 'createQueryBuilder')) {
174
            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...
175
                ->select('o')
176
                ->from($resourceClass, 'o');
177
        }
178
179
        throw new RuntimeException(
180
            sprintf(
181
                'The object manager "%s" or resource manager "%s" of the resource "%s" must have a ::createQueryBuilder() method.',
182
                get_class($resourceManager),
183
                get_class($repository),
184
                $resourceClass
185
            )
186
        );
187
    }
188
189
    private function applyIdentifiersToQueryBuilder(QueryBuilder $queryBuilder, array $identifiers)
190
    {
191
        foreach ($identifiers as $propertyName => $value) {
192
            $placeholder = 'id_'.$propertyName;
193
194
            $queryBuilder
195
                ->where($queryBuilder->expr()->eq('o.'.$propertyName, ':'.$placeholder))
196
                ->setParameter($placeholder, $value);
197
        }
198
    }
199
}
200