Skip to content

Commit

Permalink
Merge pull request #250 from delboy1978uk/master
Browse files Browse the repository at this point in the history
Add routing params to request query params for middleware usage
  • Loading branch information
philipobenito committed May 18, 2020
2 parents a15d3a5 + ebf5627 commit 1145d38
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Dispatcher.php
Expand Up @@ -42,12 +42,32 @@ public function dispatchRequest(ServerRequestInterface $request): ResponseInterf
case FastRoute::FOUND:
$route = $this->ensureHandlerIsRoute($match[1], $httpMethod, $uri)->setVars($match[2]);
$this->setFoundMiddleware($route);
$request = $this->requestWithRouteAttributes($request, $route);
break;
}

return $this->handle($request);
}

/**
* Adds routing variables as Request Attributes
*
* @param ServerRequestInterface $request
* @param Route $route
*
* @return ServerRequestInterface
*/
protected function requestWithRouteAttributes(ServerRequestInterface $request, Route $route): ServerRequestInterface
{
$routerParams = $route->getVars();

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

return $request;
}

/**
* Ensure handler is a Route, honoring the contract of dispatchRequest.
*
Expand Down
24 changes: 24 additions & 0 deletions tests/DispatchIntegrationTest.php
Expand Up @@ -43,6 +43,12 @@ public function testDispatchesFoundRoute(): void
->willReturn($uri)
;

$request
->expects($this->once())
->method('withAttribute')
->willReturn($request)
;

$router = new Router;

$router->map('GET', '/example/{something}', function (
Expand Down Expand Up @@ -93,6 +99,18 @@ public function testDispatchesExceptionRoute(): void
->willReturn('GET')
;

$request
->expects($this->any())
->method('withQueryParams')
->willReturn($request)
;

$request
->expects($this->any())
->method('withAttribute')
->willReturn($request)
;

$request
->expects($this->exactly(2))
->method('getUri')
Expand Down Expand Up @@ -988,6 +1006,12 @@ public function testDispatchDoesNotThrowWhenUsingAddRoute(): void
->willReturn($uri)
;

$request
->expects($this->any())
->method('withAttribute')
->willReturn($request)
;

$router = new Router;

$router->addRoute(['GET', 'POST'], '/example/{something}', function (
Expand Down

0 comments on commit 1145d38

Please sign in to comment.