Completed
Pull Request — master (#458)
by Théo
07:55 queued 04:49
created

ItemDataProvider::fallbackGetItem()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 18
rs 9.2
cc 4
eloc 10
nc 3
nop 4
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
     * @throws ResourceClassNotSupportedException
81
     *
82
     * @return object
83
     */
84
    private function fallbackGetItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
85
    {
86
        $manager = $this->getManagerForClass($resourceClass);
87
        $identifiers = $this->getIdentifiers($resourceClass, $id);
88
89
        if (!$fetchData || $manager instanceof EntityManagerInterface) {
90
            return $manager->getReference($resourceClass, $identifiers);
91
        }
92
93
        $queryBuilder = $this->retrieveQueryBuilder($manager, $resourceClass);
94
        $this->applyIdentifiersToQueryBuilder($queryBuilder, $identifiers);
95
96
        foreach ($this->itemExtensions as $extension) {
97
            $extension->applyToItem($queryBuilder, $resourceClass, $identifiers, $operationName);
98
        }
99
100
        return $queryBuilder->getQuery()->getOneOrNullResult();
101
    }
102
103
    /**
104
     * @param string $resourceClass
105
     *
106
     * @throws ResourceClassNotSupportedException
107
     *
108
     * @return ObjectManager
109
     */
110
    private function getManagerForClass(string $resourceClass)
111
    {
112
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
113
        if (null !== $manager) {
114
            return $manager;
115
        }
116
117
        throw new ResourceClassNotSupportedException();
118
    }
119
120
    /**
121
     * @param string     $resourceClass
122
     * @param int|string $id
123
     *
124
     * @return array Identifier values with keys as property names
125
     */
126
    private function getIdentifiers(string $resourceClass, $id)
127
    {
128
        $identifierValues = explode('-', $id);
129
        $identifiers = [];
130
        $i = 0;
131
132
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
133
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
134
135
            $identifier = $propertyMetadata->isIdentifier();
136
            if (null === $identifier || false === $identifier) {
137
                continue;
138
            }
139
140
            if (!isset($identifierValues[$i])) {
141
                throw new InvalidArgumentException(sprintf('Invalid identifier "%s".', $id));
142
            }
143
144
            $identifiers[$propertyName] = $identifierValues[$i];
145
            ++$i;
146
        }
147
148
        return $identifiers;
149
    }
150
151
    /**
152
     * @param ObjectManager $resourceManager
153
     * @param string        $resourceClass
154
     *
155
     * @throws RuntimeException
156
     *
157
     * @return \Doctrine\ORM\QueryBuilder
158
     */
159
    private function retrieveQueryBuilder(ObjectManager $resourceManager, string $resourceClass)
160
    {
161
        $repository = $resourceManager->getRepository($resourceClass);
162
163
        if ($repository instanceof EntityRepository) {
164
            return $repository->createQueryBuilder('o');
165
        }
166
167
        if ($resourceManager instanceof EntityManagerInterface) {
168
            return $resourceManager->createQueryBuilder()
169
                ->select('o')
170
                ->from($resourceClass, 'o');
171
        }
172
173
        if (method_exists($repository, 'createQueryBuilder')) {
174
            return $repository->createQueryBuilder('o');
175
        }
176
177
        if (method_exists($resourceManager, 'createQueryBuilder')) {
178
            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...
179
                ->select('o')
180
                ->from($resourceClass, 'o');
181
        }
182
183
        throw new RuntimeException(
184
            sprintf(
185
                'The object manager "%s" or resource manager "%s" of the resource "%s" must have a ::createQueryBuilder() method.',
186
                get_class($resourceManager),
187
                get_class($repository),
188
                $resourceClass
189
            )
190
        );
191
    }
192
193
    private function applyIdentifiersToQueryBuilder(QueryBuilder $queryBuilder, array $identifiers)
194
    {
195
        foreach ($identifiers as $propertyName => $value) {
196
            $placeholder = 'id_'.$propertyName;
197
198
            $queryBuilder
199
                ->where($queryBuilder->expr()->eq('o.'.$propertyName, ':'.$placeholder))
200
                ->setParameter($placeholder, $value);
201
        }
202
    }
203
}
204