ringfinger/data/classes/core/Router.php

57 lines
1.6 KiB
PHP

<?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']);
$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) . '/';
}
}