lean/src/Routing.php

51 lines
1.7 KiB
PHP

<?php
namespace Lean;
use League\Route\RouteGroup,
League\Route\Router;
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 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->fetcher->compile() 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->getRoute(), 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);
});
}
}
});
}
}