From eb9aa22170ce921d2816db539dd865986f0ba6bc Mon Sep 17 00:00:00 2001 From: Sam Light Date: Wed, 10 Jun 2026 19:00:33 +0100 Subject: testing middleware dispatch --- src/Group.php | 17 +++++++++++++++-- src/Router.php | 27 +++++++++++++-------------- 2 files changed, 28 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/Group.php b/src/Group.php index 9faae2c..7d9db95 100644 --- a/src/Group.php +++ b/src/Group.php @@ -9,12 +9,14 @@ use Lightscale\Router\Contracts\Middleware; class Group { use Concerns\HasAncestors; - use Concerns\HasMiddleware; + use Concerns\HasMiddleware { + Concerns\HasMiddleware::getMiddleware as protected traitGetMiddleware; + } /** @param Middleware[] $middleware */ public function __construct( private Router $router, - private ?Group $parent, + private ?self $parent, private ?string $prefix = null, private ?string $name = null, array $middleware = [], @@ -86,6 +88,17 @@ class Group return 0 === count($names) ? null : implode('', $names); } + /** @return Middleware[] */ + public function getMiddleware(): array + { + $r = []; + foreach ($this->getAncestorsAndSelf() as $g) { + $r = [...$r, ...$g->traitGetMiddleware()]; + } + + return $r; + } + /** @param callable(GroupDefinition): void $cb */ public function group(callable $cb): void { diff --git a/src/Router.php b/src/Router.php index d70b278..fcfc771 100644 --- a/src/Router.php +++ b/src/Router.php @@ -119,14 +119,13 @@ class Router } /** @return Middleware[] */ - private function getRouteMiddleware(Route $route): array + private function getRouteMiddleware(?Route $route): array { return [ ...$this->getMiddleware(), - ...($route->getGroup() ?? []), - ...$route->getMiddleware(), + ...($route?->getGroup()?->getMiddleware() ?? []), + ...($route?->getMiddleware() ?? []), ]; - return []; } public function dispatch(RequestInterface $request): ResponseInterface @@ -134,18 +133,18 @@ class Router $uri = $request->getUri(); $match = $this->findRoute($request->getMethod(), $uri->getPath()); - if (null === $match) { - return $this->strategy->notFound($request); - } - return $this->strategy->runMiddleware( $request, - $this->getRouteMiddleware($match->route), - fn ($request) => $this->strategy->runRoute(new RouteCall( - $request, - $match->route, - $match->segmentMatch->parameters, - )) + $this->getRouteMiddleware($match?->route), + fn ($request) => ( + null === $match ? + $this->strategy->notFound($request) : + $this->strategy->runRoute(new RouteCall( + $request, + $match->route, + $match->segmentMatch->parameters, + )) + ) ); } -- cgit v1.2.3