Added middleware support to attribute registry.

This commit is contained in:
Pachira 2023-09-08 00:09:23 +00:00
parent bb4d3e80b0
commit 923484c7ac
3 changed files with 43 additions and 16 deletions

View file

@ -1 +1 @@
0.2309.72356
0.2309.80009

View file

@ -1,7 +1,7 @@
<?php
// Route.php
// Created: 2023-09-07
// Updated: 2023-09-07
// Updated: 2023-09-08
namespace Index\Routing;
@ -13,21 +13,38 @@ use ReflectionObject;
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Route {
private ?string $method;
private string $path;
/** @internal */
public function __construct(
private string $method,
private string $path
) {}
public function __construct(string $pathOrMethod, ?string $path = null) {
if($path === null) {
$this->method = null;
$this->path = $pathOrMethod;
} else {
$this->method = $pathOrMethod;
$this->path = $path;
}
}
/**
* Returns the target method name.
*
* @return string
* @return ?string
*/
public function getMethod(): string {
public function getMethod(): ?string {
return $this->method;
}
/**
* Whether this route should be used as middleware.
*
* @return bool
*/
public function isMiddleware(): bool {
return $this->method === null;
}
/**
* Returns the target path.
*
@ -52,13 +69,12 @@ class Route {
foreach($attrInfos as $attrInfo) {
$routeInfo = $attrInfo->newInstance();
$router->add(
$routeInfo->getMethod(),
$routeInfo->getPath(),
$methodInfo->getClosure(
$methodInfo->isStatic() ? null : $handler
)
);
$closure = $methodInfo->getClosure($methodInfo->isStatic() ? null : $handler);
if($routeInfo->isMiddleware())
$router->use($routeInfo->getPath(), $closure);
else
$router->add($routeInfo->getMethod(), $routeInfo->getPath(), $closure);
}
}
}

View file

@ -1,7 +1,7 @@
<?php
// RouterTest.php
// Created: 2022-01-20
// Updated: 2023-09-07
// Updated: 2023-09-08
declare(strict_types=1);
@ -138,6 +138,16 @@ final class RouterTest extends TestCase {
return 'meow';
}
#[Route('/mw')]
public function useMw() {
return 'this intercepts';
}
#[Route('GET', '/mw')]
public function getMw() {
return 'this is intercepted';
}
public function hasNoAttr() {
return 'not a route';
}
@ -149,5 +159,6 @@ final class RouterTest extends TestCase {
$this->assertEquals('static', $router->resolve('PUT', '/static')->run());
$this->assertEquals('meow', $router->resolve('GET', '/meow')->run());
$this->assertEquals('meow', $router->resolve('POST', '/meow')->run());
$this->assertEquals('this intercepts', $router->resolve('GET', '/mw')->run());
}
}