Completed
Pull Request — master (#717)
by Antoine
06:59 queued 03:37
created

CollectionDataProvider::getQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
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\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultExtensionInterface;
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
17
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
18
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
19
use ApiPlatform\Core\Exception\RuntimeException;
20
use Doctrine\Common\Persistence\ManagerRegistry;
21
use Doctrine\ORM\Query;
22
23
/**
24
 * Collection data provider for the Doctrine ORM.
25
 *
26
 * @author Kévin Dunglas <[email protected]>
27
 * @author Samuel ROZE <[email protected]>
28
 */
29
class CollectionDataProvider implements CollectionDataProviderInterface
30
{
31
    private $managerRegistry;
32
    private $collectionExtensions;
33
    private $decorated;
34
35
    /**
36
     * @param ManagerRegistry                     $managerRegistry
37
     * @param QueryCollectionExtensionInterface[] $collectionExtensions
38
     */
39
    public function __construct(ManagerRegistry $managerRegistry, array $collectionExtensions = [], CollectionDataProviderInterface $decorated = null)
40
    {
41
        $this->managerRegistry = $managerRegistry;
42
        $this->collectionExtensions = $collectionExtensions;
43
        $this->decorated = $decorated;
44
    }
45
46
    /**
47
     * Allow to customize the Query object
48
     * For example you can force doctrine to not load lazy relations by using:
49
     * $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true).
50
     *
51
     * @param QueryBuilder
52
     * @return Query
53
     */
54
    public function getQuery(QueryBuilder $queryBuilder): Query
55
    {
56
        if ($this->decorated) {
57
            return $this->decorated->getQuery($queryBuilder);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ApiPlatform\Core\DataPro...onDataProviderInterface as the method getQuery() does only exist in the following implementations of said interface: ApiPlatform\Core\Bridge\...\CollectionDataProvider.

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...
58
        }
59
60
        return $queryBuilder->getQuery();
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function getCollection(string $resourceClass, string $operationName = null)
67
    {
68
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
69
        if (null === $manager) {
70
            throw new ResourceClassNotSupportedException();
71
        }
72
73
        $repository = $manager->getRepository($resourceClass);
74
        if (!method_exists($repository, 'createQueryBuilder')) {
75
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
76
        }
77
78
        $queryBuilder = $repository->createQueryBuilder('o');
79
        $queryNameGenerator = new QueryNameGenerator();
80
        foreach ($this->collectionExtensions as $extension) {
81
            $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
82
83
            if ($extension instanceof QueryResultExtensionInterface) {
84
                if ($extension->supportsResult($resourceClass, $operationName)) {
85
                    return $extension->getResult($queryBuilder);
86
                }
87
            }
88
        }
89
90
        return $this->getQuery($queryBuilder)->getResult();
91
    }
92
}
93