Allow repeat Route attributes.

This commit is contained in:
flash 2023-09-07 22:37:04 +00:00
parent 0710597062
commit a4e39d5e56
3 changed files with 12 additions and 22 deletions

View file

@ -1 +1 @@
0.2309.72221
0.2309.72236

View file

@ -7,12 +7,11 @@ namespace Index\Routing;
use Attribute;
use ReflectionObject;
use UnexpectedValueException;
/**
* Provides an attribute for marking methods in a class as routes.
*/
#[Attribute]
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Route {
/** @internal */
public function __construct(
@ -52,9 +51,6 @@ class Route {
$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(),

View file

@ -6,10 +6,8 @@
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use Index\Routing\IRouteHandler;
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Index\Routing\RouteHandlerTrait;
use Index\Routing\Router;
/**
@ -118,9 +116,7 @@ final class RouterTest extends TestCase {
public function testAttribute(): void {
$router = new Router;
$handler = new class implements IRouteHandler {
use RouteHandlerTrait;
$handler = new class extends RouteHandler {
#[Route('GET', '/')]
public function getIndex() {
return 'index';
@ -136,24 +132,22 @@ final class RouterTest extends TestCase {
return 'static';
}
public function hasNoAttr() {
#[Route('GET', '/meow')]
#[Route('POST', '/meow')]
public function multiple() {
return 'meow';
}
public function hasNoAttr() {
return 'not a route';
}
};
$router->register($handler);
$this->assertEquals('index', $router->resolve('GET', '/')->run());
$this->assertEquals('avatar', $router->resolve('POST', '/avatar')->run());
$this->assertEquals('static', $router->resolve('PUT', '/static')->run());
$badHandler = new class extends RouteHandler {
#[Route('GET', '/')]
#[Route('POST', '/meow')]
public function getPostBad() {
return 'this is bad';
}
};
$this->expectException(UnexpectedValueException::class);
$router->register($badHandler);
$this->assertEquals('meow', $router->resolve('GET', '/meow')->run());
$this->assertEquals('meow', $router->resolve('POST', '/meow')->run());
}
}