-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleLoader.php
More file actions
74 lines (60 loc) · 1.86 KB
/
ModuleLoader.php
File metadata and controls
74 lines (60 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace SyncEngine\Routing;
use ReflectionClass;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Contracts\Service\Attribute\Required;
use SyncEngine\Service\Locator\Modules;
class ModuleLoader extends Loader
{
private bool $isLoaded = false;
private string $root;
private Modules $modules;
#[Required]
public function init(
#[Autowire( '%syncengine.dir.modules%' )]
string $root, Modules $modules,
): void {
$this->modules = $modules;
$this->root = $root;
}
/**
* @inheritDoc
* @return RouteCollection
*/
public function load( mixed $resource, ?string $type = null ): mixed
{
if ( $this->isLoaded ) {
throw new \RuntimeException( 'Module routes already loaded' );
}
$routesCollection = new RouteCollection();
foreach ( $this->modules->getAll() as $module ) {
$reflection = new ReflectionClass( $module );
$namespace = $reflection->getNamespaceName();
$locator = $module->getClassLocator();
$module_resource = [
'path' => $this->root . '/' . $locator,
'namespace' => $namespace . '\\Controller',
];
$prefix = 'module/' . strtolower( $locator ); // Postfix with separator.
$namePrefix = str_replace( '/', '_', $prefix );
$imported = $this->import( $module_resource, 'attribute' );
foreach ( $imported as $name => $route ) {
/** @var Route $route Add module prefix and remove trailing slash */
$route->setPath( $prefix . rtrim( $route->getPath(), '/' ) );
$routesCollection->add( $namePrefix . '_' . $name, $route );
}
}
$this->isLoaded = true;
return $routesCollection;
}
/**
* @inheritDoc
*/
public function supports( mixed $resource, ?string $type = null ): bool
{
return 'syncengine_modules' === $type;
}
}