Completed
Pull Request — master (#578)
by Kévin
07:09 queued 03:03
created

CollectionDataProvider   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 6
c 2
b 1
f 0
lcom 1
cbo 5
dl 0
loc 41
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B getCollection() 0 22 5
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\DataProvider\CollectionDataProviderInterface;
17
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
18
use Doctrine\Common\Persistence\ManagerRegistry;
19
20
/**
21
 * Collection data provider for the Doctrine ORM.
22
 *
23
 * @author Kévin Dunglas <[email protected]>
24
 * @author Samuel ROZE <[email protected]>
25
 */
26
class CollectionDataProvider implements CollectionDataProviderInterface
27
{
28
    private $managerRegistry;
29
    private $collectionExtensions;
30
31
    /**
32
     * @param ManagerRegistry                     $managerRegistry
33
     * @param QueryCollectionExtensionInterface[] $collectionExtensions
34
     */
35
    public function __construct(ManagerRegistry $managerRegistry, array $collectionExtensions = [])
36
    {
37
        $this->managerRegistry = $managerRegistry;
38
        $this->collectionExtensions = $collectionExtensions;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function getCollection(string $resourceClass, string $operationName = null)
45
    {
46
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
47
        if (null === $manager) {
48
            throw new ResourceClassNotSupportedException();
49
        }
50
51
        $repository = $manager->getRepository($resourceClass);
52
        $queryBuilder = $repository->createQueryBuilder('o');
53
54
        foreach ($this->collectionExtensions as $extension) {
55
            $extension->applyToCollection($queryBuilder, $resourceClass, $operationName);
56
57
            if ($extension instanceof QueryResultExtensionInterface) {
58
                if ($extension->supportsResult($resourceClass, $operationName)) {
59
                    return $extension->getResult($queryBuilder);
60
                }
61
            }
62
        }
63
64
        return $queryBuilder->getQuery()->getResult();
65
    }
66
}
67