chore: lots of changes
This commit is contained in:
64
src/Framework/Core/RouteCompiler.php
Normal file
64
src/Framework/Core/RouteCompiler.php
Normal file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Framework\Core;
|
||||
|
||||
final class RouteCompiler
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{method: string, path: string, controller: class-string, handler: string}> $routes
|
||||
* @return array<string, array{static: array<string, array>, dynamic: array<int, array{regex: string, params: array, handler: array}>}>
|
||||
*/
|
||||
public function compile(array $routes): array
|
||||
{
|
||||
$compiled = [];
|
||||
|
||||
foreach ($routes as $route) {
|
||||
$method = strtoupper($route['http_method']);
|
||||
$path = $route['path'];
|
||||
|
||||
$compiled[$method] ??= ['static' => [], 'dynamic' => []];
|
||||
|
||||
if (! str_contains($path, '{')) {
|
||||
// Statische Route
|
||||
$compiled[$method]['static'][$path] = new StaticRoute(
|
||||
$route['class'],
|
||||
$route['method'],
|
||||
$route['parameters']
|
||||
);
|
||||
} else {
|
||||
// Dynamische Route
|
||||
$regex = $this->convertPathToRegex($path, $paramNames);
|
||||
$compiled[$method]['dynamic'][] = new DynamicRoute(
|
||||
$regex,
|
||||
$paramNames,
|
||||
$route['class'],
|
||||
$route['method'],
|
||||
$route['parameters']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $compiled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Konvertiert zB. /user/{id}/edit → ~^/user/([^/]+)/edit$~ und gibt ['id'] als Parameternamen zurück.
|
||||
*
|
||||
* @param string $path
|
||||
* @param array<string> &$paramNames
|
||||
* @return string
|
||||
*/
|
||||
private function convertPathToRegex(string $path, array &$paramNames): string
|
||||
{
|
||||
$paramNames = [];
|
||||
$regex = preg_replace_callback('#\{(\w+)\}#', function ($matches) use (&$paramNames) {
|
||||
$paramNames[] = $matches[1];
|
||||
|
||||
return '([^/]+)';
|
||||
}, $path);
|
||||
|
||||
return '~^' . $regex . '$~';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user