Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Inject the route result as an attribute #187

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,8 @@ public function routeMiddleware(ServerRequestInterface $request, ResponseInterfa
return $next($request, $response);
}

// Inject the actual route result, as well as individual matched parameters.
$request = $request->withAttribute(Router\RouteResult::class, $result);
foreach ($result->getMatchedParams() as $param => $value) {
$request = $request->withAttribute($param, $value);
}
Expand Down
31 changes: 31 additions & 0 deletions test/RouteMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -529,4 +529,35 @@ public function testWithOnlyRootPathRouteDefinedRoutingToSubPathsShouldReturn404
$this->assertInstanceOf(Response::class, $result);
$this->assertNotEquals(405, $result->getStatusCode());
}

/**
* @group 186
*/
public function testInjectsRouteResultAsAttribute()
{
$matches = ['id' => 'IDENTIFIER'];
$triggered = false;
$middleware = function ($request, $response, $next) use ($matches, &$triggered) {
$routeResult = $request->getAttribute(RouteResult::class, false);
$this->assertInstanceOf(RouteResult::class, $routeResult);
$this->assertTrue($routeResult->isSuccess());
$this->assertSame($matches, $routeResult->getMatchedParams());
$triggered = true;
return $response;
};
$next = function ($request, $response, $err = null) {
$this->fail('Should not hit next');
};

$request = new ServerRequest();
$response = new Response();
$result = RouteResult::fromRouteMatch('resource', $middleware, $matches);

$this->router->match($request)->willReturn($result);

$app = $this->getApplication();
$test = $app->routeMiddleware($request, $response, $next);
$this->assertSame($response, $test);
$this->assertTrue($triggered);
}
}