misuzu/src/Routing/HandlerRoles.php

36 lines
1 KiB
PHP

<?php
namespace Misuzu\Routing;
use Attribute;
use ReflectionAttribute;
use ReflectionObject;
use Index\Http\Routing\{Router,RouteHandler as IndexRouteHandler};
#[Attribute(Attribute::TARGET_CLASS)]
final class HandlerRoles {
/** @var string[] $roles */
public private(set) array $roles;
public function __construct(string ...$roles) {
$this->roles = $roles;
}
public function hasRole(string $role): bool {
return in_array($role, $this->roles);
}
/** @param string[] $roles */
public static function register(Router $router, IndexRouteHandler $handler, array $roles): void {
$object = new ReflectionObject($handler);
$attrs = $object->getAttributes(self::class, ReflectionAttribute::IS_INSTANCEOF);
if(empty($attrs))
return;
$info = $attrs[0]->newInstance();
foreach($roles as $role)
if($info->hasRole($role)) {
$handler->registerRoutes($router);
break;
}
}
}