51 lines
1.4 KiB
PHP
51 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace KTXC\Http\Middleware;
|
|
|
|
use KTXC\Http\Request\Request;
|
|
use KTXC\Http\Response\Response;
|
|
use KTXC\Routing\Router;
|
|
use KTXC\Routing\Route;
|
|
use KTXC\SessionIdentity;
|
|
|
|
/**
|
|
* Router middleware
|
|
* Matches routes and dispatches to controllers
|
|
*/
|
|
class RouterMiddleware implements MiddlewareInterface
|
|
{
|
|
public function __construct(
|
|
private readonly Router $router,
|
|
private readonly SessionIdentity $sessionIdentity
|
|
) {}
|
|
|
|
public function process(Request $request, RequestHandlerInterface $handler): Response
|
|
{
|
|
// Attempt to match the route
|
|
$match = $this->router->match($request);
|
|
|
|
if (!$match instanceof Route) {
|
|
// No route matched, continue to next handler (will return 404)
|
|
return $handler->handle($request);
|
|
}
|
|
|
|
// Check if route requires authentication
|
|
if ($match->authenticated && $this->sessionIdentity->identity() === null) {
|
|
return new Response(
|
|
Response::$statusTexts[Response::HTTP_UNAUTHORIZED],
|
|
Response::HTTP_UNAUTHORIZED
|
|
);
|
|
}
|
|
|
|
// Dispatch to the controller
|
|
$response = $this->router->dispatch($match, $request);
|
|
|
|
if ($response instanceof Response) {
|
|
return $response;
|
|
}
|
|
|
|
// If dispatch didn't return a response, continue to next handler
|
|
return $handler->handle($request);
|
|
}
|
|
}
|