ringfinger/backend/classes/core/Router.php

58 lines
1.3 KiB
PHP
Raw Permalink Normal View History

2020-08-17 23:46:58 +02:00
<?php
declare(strict_types=1);
final class Router
{
2020-08-23 12:37:39 +02:00
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']);
/** @var AbstractController $controller */
$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) . '/';
}
2020-08-17 23:46:58 +02:00
}