Skip to content

Commit

Permalink
add matched route parameters to server request
Browse files Browse the repository at this point in the history
  • Loading branch information
IngeniozIT committed Oct 7, 2023
1 parent 955b17c commit 8c120c0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,33 @@ public function __construct(
public function handle(ServerRequestInterface $request): ResponseInterface
{
foreach ($this->routeGroup->routes as $route) {
if ($route->match($request) === false) {
$matchedParams = $route->match($request);
if ($matchedParams === false) {
continue;
}

$newRequest = $request;
foreach ($matchedParams as $key => $value) {
$newRequest = $newRequest->withAttribute($key, $value);
}

/** @var object $callback */
$callback = is_string($route->callback) ?
$this->container->get($route->callback) :
$route->callback;
if ($callback instanceof RequestHandlerInterface) {
return $callback->handle($request);
return $callback->handle($newRequest);
}

if ($callback instanceof MiddlewareInterface) {
return $callback->process($request, $this);
return $callback->process($newRequest, $this);
}

if (!is_callable($callback)) {
throw new InvalidRoute('Route callback is not callable.');
}

return $callback($request, $this);
return $callback($newRequest, $this);
}

if (!$this->fallback instanceof \Closure) {
Expand Down
16 changes: 16 additions & 0 deletions tests/RouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,22 @@ public function testFiltersOutRoutesWithWrongMethod(): void
self::assertEquals('TEST2', (string) $response->getBody());
}

public function testAddsMatchedParametersToRequest(): void
{
$routeGroup = new RouteGroup(routes: [
Route::get(
path: '/{foo}',
callback: static fn(ServerRequestInterface $request): ResponseInterface =>
self::response(var_export($request->getAttribute('foo'), true))
),
]);
$request = self::serverRequest('GET', '/bar');

$response = $this->router($routeGroup)->handle($request);

self::assertEquals("'bar'", (string) $response->getBody());
}

public function testMustFindARouteToProcess(): void
{
$routeGroup = new RouteGroup(routes: [
Expand Down

0 comments on commit 8c120c0

Please sign in to comment.