|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jidaikobo\Kontiki\Services; |
|
4
|
|
|
|
|
5
|
|
|
use Slim\Interfaces\RouteCollectorInterface; |
|
6
|
|
|
|
|
7
|
|
|
class RoutesService |
|
8
|
|
|
{ |
|
9
|
|
|
private RouteCollectorInterface $routeCollector; |
|
10
|
|
|
private array $routesCache = []; |
|
11
|
|
|
|
|
12
|
|
|
public function __construct( |
|
13
|
|
|
RouteCollectorInterface $routeCollector |
|
14
|
|
|
) { |
|
15
|
|
|
$this->routeCollector = $routeCollector; |
|
16
|
|
|
$this->cacheRoutes(); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
private function cacheRoutes(): void |
|
20
|
|
|
{ |
|
21
|
|
|
$routes = $this->routeCollector->getRoutes(); |
|
22
|
|
|
$this->routesCache = []; |
|
23
|
|
|
|
|
24
|
|
|
foreach ($routes as $route) { |
|
25
|
|
|
$controller = $this->extractControllerFromPattern($route->getPattern()); |
|
26
|
|
|
|
|
27
|
|
|
$name = $route->getName() ?? ''; |
|
28
|
|
|
[$routeName, $langStyle, $types] = explode('|', $name) + [null, '', '']; |
|
29
|
|
|
$englishStyle = str_replace('x_', ':name ', $langStyle); |
|
30
|
|
|
$name = $langStyle ? __($langStyle, $englishStyle, ['name' => __($routeName)]) : null; |
|
31
|
|
|
|
|
32
|
|
|
$this->routesCache[$controller][] = [ |
|
33
|
|
|
'methods' => implode(', ', $route->getMethods()), |
|
34
|
|
|
'path' => env('BASEPATH') . $route->getPattern(), |
|
35
|
|
|
'name' => $name, |
|
36
|
|
|
'type' => explode(',', $types) |
|
37
|
|
|
]; |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function getRoutes(): array |
|
42
|
|
|
{ |
|
43
|
|
|
return $this->routesCache; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public function getRoutesByController(string $controller): array |
|
47
|
|
|
{ |
|
48
|
|
|
$target = $controller; |
|
49
|
|
|
if (strpos($controller, '/') !== false) { |
|
50
|
|
|
$controllerSegments = explode('/', $controller); |
|
51
|
|
|
$target = reset($controllerSegments); |
|
52
|
|
|
} |
|
53
|
|
|
return $this->routesCache[$target] ?? []; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function getRoutesByType(string $type): array |
|
57
|
|
|
{ |
|
58
|
|
|
$filtered = array_filter(array_map(function ($routes) use ($type) { |
|
59
|
|
|
return array_filter($routes, function ($route) use ($type) { |
|
60
|
|
|
return in_array($type, $route['type'], true); |
|
61
|
|
|
}); |
|
62
|
|
|
}, $this->routesCache)); |
|
63
|
|
|
return $filtered; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Extract the controller name from the route pattern. |
|
68
|
|
|
* |
|
69
|
|
|
* @param string $pattern The route pattern (e.g., "/users"). |
|
70
|
|
|
* @return string The extracted controller name (e.g., "users"). |
|
71
|
|
|
*/ |
|
72
|
|
|
private function extractControllerFromPattern(string $pattern): string |
|
73
|
|
|
{ |
|
74
|
|
|
$segments = explode('/', trim($pattern, '/')); |
|
75
|
|
|
return $segments[0]; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|