index/src/Http/Routing/HandlerAttribute.php
2024-03-28 20:14:54 +00:00

52 lines
1.5 KiB
PHP

<?php
// HandlerAttribute.php
// Created: 2024-03-28
// Updated: 2024-03-28
namespace Index\Http\Routing;
use Attribute;
use ReflectionObject;
/**
* Provides an attribute for marking methods in a class as handlers.
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class HandlerAttribute {
public function __construct(private string $path) {}
/**
* Returns the target path.
*
* @return string
*/
public function getPath(): string {
return $this->path;
}
/**
* Reads attributes from methods in a IRouteHandler instance and registers them to a given IRouter instance.
*
* @param IRouter $router Router instance.
* @param IRouteHandler $handler Handler instance.
*/
public static function register(IRouter $router, IRouteHandler $handler): void {
$objectInfo = new ReflectionObject($handler);
$methodInfos = $objectInfo->getMethods();
foreach($methodInfos as $methodInfo) {
$attrInfos = $methodInfo->getAttributes(HandlerAttribute::class);
foreach($attrInfos as $attrInfo) {
$handlerInfo = $attrInfo->newInstance();
$closure = $methodInfo->getClosure($methodInfo->isStatic() ? null : $handler);
if($handlerInfo instanceof HttpRoute)
$router->add($handlerInfo->getMethod(), $handlerInfo->getPath(), $closure);
else
$router->use($handlerInfo->getPath(), $closure);
}
}
}
}