Added abstract RouteHandler and documentation.

This commit is contained in:
flash 2023-09-07 22:22:41 +00:00
parent 32254bf398
commit 0710597062
6 changed files with 50 additions and 5 deletions

View file

@ -1 +1 @@
0.2309.72158
0.2309.72221

View file

@ -1,10 +1,18 @@
<?php
// IRouteHandler.php
// Created: 2023-09-06
// Updated: 2023-09-06
// Updated: 2023-09-07
namespace Index\Routing;
/**
* Provides the interface for IRouter::register().
*/
interface IRouteHandler {
/**
* Registers routes on a given IRouter instance.
*
* @param IRouter $router Target router.
*/
public function registerRoutes(IRouter $router): void;
}

View file

@ -9,21 +9,41 @@ use Attribute;
use ReflectionObject;
use UnexpectedValueException;
/**
* Provides an attribute for marking methods in a class as routes.
*/
#[Attribute]
class Route {
/** @internal */
public function __construct(
private string $method,
private string $path
) {}
/**
* Returns the target method name.
*
* @return string
*/
public function getMethod(): string {
return $this->method;
}
/**
* 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 handleAttributes(IRouter $router, IRouteHandler $handler): void {
$objectInfo = new ReflectionObject($handler);
$methodInfos = $objectInfo->getMethods();

View file

@ -0,0 +1,14 @@
<?php
// RouteHandler.php
// Created: 2023-09-07
// Updated: 2023-09-07
namespace Index\Routing;
/**
* Provides an abstract class version of IRouteHandler that already includes the trait as well,
* letting you only have to use one use statement rather than two!
*/
abstract class RouteHandler implements IRouteHandler {
use RouteHandlerTrait;
}

View file

@ -5,6 +5,10 @@
namespace Index\Routing;
/**
* Provides an implementation of IRouteHandler::registerRoutes that uses the attributes.
* For more advanced use, everything can be use'd separately and Route::handleAttributes called manually.
*/
trait RouteHandlerTrait {
public function registerRoutes(IRouter $router): void {
Route::handleAttributes($router, $this);

View file

@ -8,6 +8,7 @@ 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;
@ -145,9 +146,7 @@ final class RouterTest extends TestCase {
$this->assertEquals('avatar', $router->resolve('POST', '/avatar')->run());
$this->assertEquals('static', $router->resolve('PUT', '/static')->run());
$badHandler = new class implements IRouteHandler {
use RouteHandlerTrait;
$badHandler = new class extends RouteHandler {
#[Route('GET', '/')]
#[Route('POST', '/meow')]
public function getPostBad() {