55 lines
1.6 KiB
PHP
55 lines
1.6 KiB
PHP
<?php
|
|
// HandlerAttribute.php
|
|
// Created: 2024-03-28
|
|
// Updated: 2024-08-01
|
|
|
|
namespace Index\Http\Routing;
|
|
|
|
use ReflectionAttribute;
|
|
use ReflectionObject;
|
|
|
|
/**
|
|
* Provides base for attributes that mark methods in a class as handlers.
|
|
*/
|
|
abstract class HandlerAttribute {
|
|
/**
|
|
* @param string $path Target path.
|
|
*/
|
|
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, ReflectionAttribute::IS_INSTANCEOF);
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|