-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMenuLoader.php
More file actions
94 lines (75 loc) · 2.29 KB
/
MenuLoader.php
File metadata and controls
94 lines (75 loc) · 2.29 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace SyncEngine\Service\Menu;
use ReflectionClass;
use ReflectionMethod;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\Cache\ItemInterface;
use SyncEngine\Attribute\MenuItem;
use SyncEngine\Service\Cache\FilesystemCache;
class MenuLoader
{
public function __construct(
private readonly ServiceLocator $container,
private readonly FilesystemCache $cache,
private readonly KernelInterface $kernel,
) {}
public function getMenuItems( string $menu ): MenuItemCollection
{
if ( $this->kernel->isDebug() ) {
$items = $this->loadMenuItems();
} else {
$items = $this->cache->get( 'MenuLoader_MenuItems', function( ItemInterface &$item ) {
return $this->loadMenuItems();
} );
}
$collection = new MenuItemCollection();
foreach ( $items as $item ) {
if ( $item->getMenu() === $menu ) {
$collection->add( $item );
}
}
return $collection;
}
protected function loadMenuItems()
{
$items = [];
$controllers = $this->container->getProvidedServices();
foreach ( $controllers as $tag => $service ) {
$controller = $this->container->get( $tag );
$items = array_merge( $items, $this->getControllerMenuItems( $controller ) );
}
return $items;
}
protected function getControllerMenuItems( AbstractController $controller ): array
{
$refClass = new ReflectionClass( $controller );
$items = $this->getMenuItemAttributes( $refClass );
foreach ( $refClass->getMethods( ReflectionMethod::IS_PUBLIC ) as $method ) {
// Only use own methods, not inherited.
if ( $method->getFileName() === $refClass->getFileName() ) {
$items = array_merge( $items, $this->getMenuItemAttributes( $method ) );
}
}
return $items;
}
/**
* @param ReflectionMethod|ReflectionClass $reflection
*
* @return MenuItem[]
*/
protected function getMenuItemAttributes( ReflectionMethod|ReflectionClass $reflection ): array
{
$menuItems = $reflection->getAttributes( MenuItem::class, \ReflectionAttribute::IS_INSTANCEOF );
if ( empty( $menuItems ) ) {
return [];
}
$items = [];
foreach ( $menuItems as $attribute ) {
/** @var MenuItem $item */
$items[] = $attribute->newInstance();
}
return $items;
}
}