website/lib/Framework/Router.php

69 lines
2.7 KiB
PHP
Raw Normal View History

2021-08-05 13:51:44 +02:00
<?php
namespace JeroenED\Framework;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Filesystem\Exception\InvalidArgumentException;
2021-08-06 12:30:00 +02:00
use Symfony\Component\HttpFoundation\RedirectResponse;
2021-08-05 13:51:44 +02:00
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
2021-08-06 12:30:00 +02:00
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
2021-08-05 13:51:44 +02:00
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
class Router
{
private RouteCollection $routes;
private RequestContext $requestContext;
public function route(Request $request, Kernel $kernel): Response
{
2021-08-06 12:30:00 +02:00
try {
// Here be dragons
$requestContext = new RequestContext();
$this->requestContext = $requestContext->fromRequest($request);
$matcher = new UrlMatcher($this->routes, $this->requestContext);
$method = $matcher->match($request->getPathInfo());
$controller = explode('::', $method['_controller']);
$controllerObj = new ('\\' . $controller[0])($request, $kernel);
$action = $controller[1];
unset($method['_controller']);
unset($method['_route']);
$response = $controllerObj->$action(...$method);
if ($response instanceof Response) {
2022-02-01 14:29:41 +01:00
$response->headers->add([
2022-03-31 13:51:38 +02:00
"Content-Security-Policy" => "default-src 'none'; font-src 'self'; style-src 'self'; script-src 'self'; img-src 'self'; form-action 'none'; frame-ancestors 'none'; require-trusted-types-for 'script'; base-uri 'none'; ",
"Referrer-Policy" => "same-origin"
2022-02-01 14:29:41 +01:00
]);
2021-08-06 12:30:00 +02:00
return $response;
} else {
throw new InvalidArgumentException();
}
} catch(ResourceNotFoundException $e) {
return new RedirectResponse($this->getUrlForRoute('error', ['status' => '404']));
} catch (\Throwable $e) {
return new RedirectResponse($this->getUrlForRoute('error', ['status' => (method_exists($e,'getStatusCode')) ? $e->getStatusCode() : '500']));
2021-08-05 13:51:44 +02:00
}
}
public function parseRoutes(string $dir, string $file): void
{
$routeloader = new YamlFileLoader(new FileLocator($dir));
$this->routes = $routeloader->load($file);
}
public function getUrlForRoute(string $route, array $params = []): string
{
$matcher = new UrlGenerator($this->routes, $this->requestContext);
return $matcher->generate($route, $params, UrlGenerator::ABSOLUTE_URL);
}
}