index/src/Routing/Route.php

50 lines
1.3 KiB
PHP

<?php
// Route.php
// Created: 2023-09-07
// Updated: 2023-09-07
namespace Index\Routing;
use Attribute;
use ReflectionObject;
use UnexpectedValueException;
#[Attribute]
class Route {
public function __construct(
private string $method,
private string $path
) {}
public function getMethod(): string {
return $this->method;
}
public function getPath(): string {
return $this->path;
}
public static function handleAttributes(IRouter $router, IRouteHandler $handler): void {
$objectInfo = new ReflectionObject($handler);
$methodInfos = $objectInfo->getMethods();
foreach($methodInfos as $methodInfo) {
$attrInfos = $methodInfo->getAttributes(Route::class);
foreach($attrInfos as $attrInfo) {
if($attrInfo->isRepeated())
throw new UnexpectedValueException('Only one instance of the Route attribute should be used per method.');
$routeInfo = $attrInfo->newInstance();
$router->add(
$routeInfo->getMethod(),
$routeInfo->getPath(),
$methodInfo->getClosure(
$methodInfo->isStatic() ? null : $handler
)
);
}
}
}
}