Passed
Push — develop ( 74761d...9bb873 )
by Daniel
06:04
created

LayoutDataProvider   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 84.62%

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 11
cts 13
cp 0.8462
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A supports() 0 3 1
A getItem() 0 13 3
1
<?php
2
3
namespace Silverback\ApiComponentBundle\DataProvider\Item;
4
5
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
6
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
7
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
8
use Doctrine\Common\Persistence\ManagerRegistry;
9
use Silverback\ApiComponentBundle\Entity\Layout\Layout;
10
11
final class LayoutDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
12
{
13
    /**
14
     * @var ManagerRegistry
15
     */
16
    private $managerRegistry;
17
18
    /**
19
     * LayoutDataProvider constructor.
20
     *
21
     * @param ManagerRegistry $managerRegistry
22
     */
23 4
    public function __construct(ManagerRegistry $managerRegistry)
24
    {
25 4
        $this->managerRegistry = $managerRegistry;
26 4
    }
27
28
    /**
29
     * @param string $resourceClass
30
     * @param string|null $operationName
31
     * @param array $context
32
     * @return bool
33
     */
34 4
    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
35
    {
36 4
        return $resourceClass === Layout::class;
37
    }
38
39
    /**
40
     * @param string $resourceClass
41
     * @param int|string $id
42
     * @param string|null $operationName
43
     * @param array $context
44
     * @return Layout|null
45
     * @throws ResourceClassNotSupportedException
46
     */
47 1
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = [])
48
    {
49 1
        if ($id !== 'default') {
50
            throw new ResourceClassNotSupportedException('LayoutDataProvider only supports the id `default`');
51
        }
52 1
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
53 1
        if (null === $manager) {
54
            throw new ResourceClassNotSupportedException(sprintf('No manager for the class `%s`', $resourceClass));
55
        }
56
        // Ideally we should probably just get the id of the default layout and then forward that onto the default data provider
57
        // But we don't want to do an un-necessary database lookup - perhaps as the default layout is saved we update a persistent variable somewhere...
58 1
        $repository = $manager->getRepository($resourceClass);
59 1
        return $repository->findOneBy(['default' => true]);
60
    }
61
}
62