ringfinger/backend/classes/core/Router.php

58 lines
1.6 KiB
PHP
Raw Normal View History

2020-08-17 23:46:58 +02:00
<?php
declare(strict_types=1);
final class Router
{
private string $route;
private string $method;
private ?string $requestBody = null;
private ?string $contentType = null;
public function __construct(string $route, string $method)
{
$this->route = $route;
$this->method = $method;
}
public function setRequestBody(string $contentType, string $content): void
{
$this->contentType = $contentType;
$this->requestBody = $content;
}
public function route(): void
{
foreach (ROUTES[$this->method] as $route => $params) {
preg_match_all($this->createRegex($route, $params['params']), $this->route, $matches);
if (count($matches[0]) > 0) {
$class = new ReflectionClass($params['controller']);
2020-08-19 21:06:45 +02:00
/** @var AbstractController $controller */
2020-08-17 23:46:58 +02:00
$controller = $class->newInstance($matches[0][0]);
if ($this->requestBody !== null && $this->contentType !== null) {
$controller->setRequestBody($this->contentType, $this->requestBody);
}
$controller->handle();
$controller->getResponse()->respond();
return;
}
}
}
private function createRegex(string $route, array $params): string
{
foreach ($params as $param => $values) {
switch ($values['type']) {
case 'int':
$route = str_replace('{' . $param . '}', '[0-9]+', $route);
}
}
return '/' . str_replace('/', '\\/', $route) . '/';
}
}