90 lines
2.8 KiB
PHP
90 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace Lean;
|
|
|
|
use League\Route\RouteGroup,
|
|
League\Route\Router;
|
|
|
|
use Notes\Route\Attribute\Method\Route;
|
|
use Psr\Http\Message\ServerRequestInterface,
|
|
Psr\Http\Message\ResponseInterface,
|
|
Psr\Container\ContainerInterface;
|
|
|
|
use Notes\Route\RouteFetcher;
|
|
|
|
use Mcnd\Event\EventManager;
|
|
|
|
class Routing {
|
|
|
|
public ResponseInterface $response;
|
|
|
|
public array $overriddenRoutes = [];
|
|
|
|
public function __construct(
|
|
public Router $router,
|
|
public RouteFetcher $fetcher,
|
|
public EventManager $eventManager,
|
|
) { }
|
|
|
|
public function registerRoute(ContainerInterface $container, string $urlBase) {
|
|
$this->router->group(rtrim($urlBase, "/"), function (RouteGroup $route) use ($container) {
|
|
foreach($this->fetchRoutesAttributes() as $attribute) {
|
|
$this->eventManager->execute(Event\RoutingCompileRoutes::class, $this, $attribute);
|
|
|
|
# Mapping every URLs from attributes in searched folders (Api, Controller, etc...)
|
|
foreach((array) $attribute->method as $method) {
|
|
$route->map(strtoupper($method), $attribute->getRegistrableRoute(), function (ServerRequestInterface $request, array $arguments) use (
|
|
$container, $route, $attribute
|
|
) : ResponseInterface {
|
|
$class = $attribute->class;
|
|
$method = $attribute->classMethod;
|
|
$object = $container->get($class);
|
|
|
|
$this->eventManager->execute(Event\RoutingMapRoutes::class, $this, $container, $request, $attribute);
|
|
|
|
$container->set(ServerRequestInterface::class, $request);
|
|
|
|
return $this->response ?? $object->$method($request, $arguments);
|
|
});
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
public function fetchRoutesAttributes() : iterable
|
|
{
|
|
static $list = [];
|
|
|
|
if ($list) {
|
|
return $list;
|
|
}
|
|
|
|
foreach($this->fetcher->compile() as $routeAttribute) {
|
|
# Routes with differents methods can have the same name
|
|
$key = sprintf('{%s}~{%s}', $routeAttribute->name, $this->serializeMethods((array) $routeAttribute->method));
|
|
|
|
if ( isset($list[$key]) ) {
|
|
$this->overriddenRoutes[$key] = $list[$key];
|
|
}
|
|
|
|
$list[$key] = $routeAttribute;
|
|
}
|
|
|
|
return $list;
|
|
}
|
|
|
|
public function findOverriddenRoute(Route $route) : false|iterable
|
|
{
|
|
return array_filter($this->overriddenRoutes, fn($e) => $route->name === $e->name);
|
|
}
|
|
|
|
protected function serializeMethods(array $methods) : string
|
|
{
|
|
$methods = array_map('strtolower', $methods);
|
|
|
|
sort($methods);
|
|
|
|
return implode(':', $methods);
|
|
}
|
|
}
|