lean/src/Routing.php

115 lines
3.8 KiB
PHP
Raw Normal View History

<?php
namespace Lean;
use Taxus\Taxus;
use League\Route\RouteGroup,
League\Route\Router;
use Psr\Http\Message\ServerRequestInterface,
Psr\Http\Message\ResponseInterface,
Psr\Container\ContainerInterface;
use Notes\Route\RouteFetcher;
use Notes\Security\SecurityHandler;
use Notes\Tell\LanguageHandler;
use Picea\Picea,
Picea\Extension\UrlExtension;
use Storage\Cookie,
Storage\Session;
use function DI\autowire, DI\create;
class Routing {
protected Session $session;
protected Cookie $cookie;
protected UrlExtension $extension;
protected RouteFetcher $fetcher;
protected SecurityHandler $security;
protected LanguageHandler $language;
protected Taxus $taxus;
public function __construct(
Session $session,
Cookie $cookie,
UrlExtension $extension,
Router $router,
RouteFetcher $routeFetcher,
SecurityHandler $security,
LanguageHandler $language,
Taxus $taxus
)
{
$this->session = $session;
$this->cookie = $cookie;
$this->extension = $extension;
$this->fetcher = $routeFetcher;
$this->security = $security;
$this->language = $language;
$this->router = $router;
$this->taxus = $taxus;
}
public function registerRoute(ContainerInterface $container, string $urlBase) {
$this->router->group(rtrim($urlBase, "/"), function (RouteGroup $route) use ($container) {
foreach($this->fetcher->compile() as $annotation) {
# Register routes to the UrlExtension from picea (handling url, route and asset extensions)
if ( null !== ( $name = $annotation->name ?? null ) ) {
$this->extension->registerRoute($name, $annotation->getRoute(), $annotation->class, $annotation->classMethod, $annotation->methods ?? (array) $annotation->method);
}
foreach((array) ( $annotation->method ?? $annotation->methods ) as $method) {
# Mapping every URLs from annotations in searched folders (Api, Controller, etc...)
$route->map(strtoupper($method), $annotation->getRoute(), function (ServerRequestInterface $request, array $arguments) use (
$container, $route, $annotation
) : ResponseInterface
{
$class = $annotation->class;
$method = $annotation->classMethod;
# $container->set($class, autowire($class)->method($method, $request));
if ( null !== ( $languageAnnotation = $this->language->verify($class) ) ) {
if ( $languageAnnotation->key ) {
# TODO !!! $language
}
}
$object = $container->get($class);
# Checking if user needs to be logged
if ( ( $redirect = $this->security->verify($class, $method) ) && ( empty($object->user) || ! $object->user->logged ) ) {
$this->session->redirectedFrom = (string) $request->getUri();
return $redirect;
}
if ( $forbidden = $this->security->taxus($class, $method, $object->user) ) {
return $forbidden;
}
if ( $container->has(Picea::class) ) {
$container->get(Picea::class)->globalVariables['route'] = $annotation;
}
return $object->$method($request->withAttribute('lean.route', $annotation), $arguments);
});
}
}
});
}
}