RoutingLoader::loadResource()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 21
rs 9.8666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LAG\AdminBundle\Routing\Loader;
6
7
use LAG\AdminBundle\Metadata\AdminResource;
8
use LAG\AdminBundle\Resource\Registry\ResourceRegistryInterface;
9
use LAG\AdminBundle\Routing\UrlGenerator\UrlGeneratorInterface;
10
use Symfony\Component\Config\Loader\Loader;
11
use Symfony\Component\Routing\Route;
12
use Symfony\Component\Routing\RouteCollection;
13
14
class RoutingLoader extends Loader
15
{
16
    private bool $loaded = false;
17
18
    public function __construct(
19
        private ResourceRegistryInterface $resourceRegistry,
20
        private UrlGeneratorInterface $urlGenerator,
21
    ) {
22
        parent::__construct();
23
    }
24
25
    public function load(mixed $resource, string $type = null): RouteCollection
26
    {
27
        if ($this->loaded) {
28
            throw new \RuntimeException('Do not add the Admin routing loader "lag_admin" twice');
29
        }
30
        $routes = new RouteCollection();
31
        $resources = $this->resourceRegistry->all();
32
33
        foreach ($resources as $resource) {
34
            $this->loadResource($resource, $routes);
35
        }
36
37
        return $routes;
38
    }
39
40
    public function supports($resource, string $type = null): bool
41
    {
42
        return 'lag_admin' === $type;
43
    }
44
45
    private function loadResource(AdminResource $resource, RouteCollection $routes): void
46
    {
47
        $identifiers = [];
48
49
        foreach ($resource->getIdentifiers() as $identifier) {
50
            $identifiers[$identifier] = null;
51
        }
52
53
        foreach ($resource->getOperations() as $operation) {
54
            $routes->add($operation->getRoute(), new Route(
55
                $this->urlGenerator->generatePath($resource, $operation),
56
                [
57
                    '_controller' => $operation->getController(),
58
                    '_admin' => $operation->getResourceName(),
59
                    '_action' => $operation->getName(),
60
                ],
61
                [],
62
                $identifiers,
63
                null,
64
                [],
65
                $operation->getMethods(),
66
            ));
67
        }
68
    }
69
}
70