Passed
Pull Request — master (#374)
by Arnaud
32:43 queued 25:11
created

ResourceRegistry::getResourceNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 1
c 1
b 1
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LAG\AdminBundle\Resource\Registry;
6
7
use LAG\AdminBundle\Exception\Exception;
8
use LAG\AdminBundle\Exception\UnexpectedTypeException;
9
use LAG\AdminBundle\Metadata\AdminResource;
10
use LAG\AdminBundle\Metadata\Factory\ResourceFactoryInterface;
11
use LAG\AdminBundle\Metadata\Locator\MetadataLocatorInterface;
12
13
class ResourceRegistry implements ResourceRegistryInterface
14
{
15
    /** @var AdminResource[] */
16
    private array $definitions = [];
17
    private bool $loaded = false;
18
19
    public function __construct(
20
        /** @var array<int, string> $resourcePaths */
21
        private array $resourcePaths,
22
        private MetadataLocatorInterface $locator,
23
        private ResourceFactoryInterface $resourceFactory,
24
    ) {
25
    }
26
27
    public function load(): void
28
    {
29
        if ($this->loaded) {
30
            return;
31
        }
32
33
        foreach ($this->resourcePaths as $path) {
34
            $resources = $this->locator->locateCollection($path);
35
36
            foreach ($resources as $resource) {
37
                if (!$resource instanceof AdminResource) {
38
                    throw new UnexpectedTypeException($resource, AdminResource::class);
39
                }
40
41
                if (!$resource->getName()) {
42
                    throw new Exception('The admin resource has no name');
43
                }
44
                $this->definitions[$resource->getName()] = $resource;
45
            }
46
        }
47
        $this->loaded = true;
48
    }
49
50
    public function has(string $resourceName): bool
51
    {
52
        return \array_key_exists($resourceName, $this->definitions);
53
    }
54
55
    public function get(string $resourceName): AdminResource
56
    {
57
        $this->load();
58
59
        if (!$this->has($resourceName)) {
60
            throw new Exception('Resource with name "'.$resourceName.'" not found');
61
        }
62
63
        return $this->resourceFactory->create($this->definitions[$resourceName]);
64
    }
65
66
    public function all(): iterable
67
    {
68
        $this->load();
69
70
        foreach ($this->definitions as $definition) {
71
            yield $this->resourceFactory->create($definition);
72
        }
73
    }
74
}
75