|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Copyright (c) 2020. |
|
4
|
|
|
* @author Paweł Antosiak <[email protected]> |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Gorynych\Resource; |
|
8
|
|
|
|
|
9
|
|
|
use Gorynych\Exception\NotExistentResourceException; |
|
10
|
|
|
use Gorynych\Operation\ResourceOperationInterface; |
|
11
|
|
|
use Symfony\Component\Config\FileLocatorInterface; |
|
12
|
|
|
use Symfony\Component\DependencyInjection\ContainerInterface; |
|
13
|
|
|
use Symfony\Component\Yaml\Yaml; |
|
14
|
|
|
|
|
15
|
|
|
final class ResourceLoader |
|
16
|
|
|
{ |
|
17
|
|
|
private ContainerInterface $container; |
|
18
|
|
|
/** @var string[][] */ |
|
19
|
|
|
private array $resourceRegistry; |
|
20
|
|
|
|
|
21
|
2 |
|
public function __construct(ContainerInterface $container, FileLocatorInterface $fileLocator) |
|
22
|
|
|
{ |
|
23
|
2 |
|
$this->container = $container; |
|
24
|
2 |
|
$this->resourceRegistry = $this->parseResourceRegistry($fileLocator->locate('resources.yaml')); |
|
|
|
|
|
|
25
|
2 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @return string[] |
|
29
|
|
|
*/ |
|
30
|
|
|
public function getResources(): array |
|
31
|
|
|
{ |
|
32
|
|
|
return array_keys($this->resourceRegistry); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Loads resource by given classname |
|
37
|
|
|
* |
|
38
|
|
|
* @throws NotExistentResourceException |
|
39
|
|
|
*/ |
|
40
|
2 |
|
public function loadResource(string $resourceClass): AbstractResource |
|
41
|
|
|
{ |
|
42
|
2 |
|
if (false === array_key_exists($resourceClass, $this->resourceRegistry)) { |
|
43
|
1 |
|
throw new NotExistentResourceException($resourceClass); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** @var AbstractResource $resource */ |
|
47
|
1 |
|
$resource = $this->container->get($resourceClass); |
|
48
|
|
|
|
|
49
|
1 |
|
foreach ($this->resourceRegistry[$resourceClass] as $operationClass) { |
|
50
|
|
|
/** @var ResourceOperationInterface $operation */ |
|
51
|
1 |
|
$operation = $this->container->get($operationClass); |
|
52
|
1 |
|
$resource->addOperation($operation); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
return $resource; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @return string[][] |
|
60
|
|
|
*/ |
|
61
|
2 |
|
private function parseResourceRegistry(string $file): array |
|
62
|
|
|
{ |
|
63
|
2 |
|
return Yaml::parseFile($file)['resources']; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|