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

Commit 02c489b

Browse files
committed
Merge branch 'hotfix/344'
Close #344
2 parents ae42a16 + 4cf97fc commit 02c489b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

doc/book/features/router/intro.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,51 @@ matched:
3131
$id = $request->getAttribute('id');
3232
```
3333

34+
## Retrieving the matched route
35+
36+
When routing is successful, the routing middleware injects a
37+
`Zend\Expressive\Router\RouteResult` instance as a request attribute, using that
38+
class name as the attribute name. The `RouteResult` instance provides you access
39+
to the following:
40+
41+
- The matched route name, via `$result->getMatchedRouteName()`.
42+
- The matched middleware, via `$result->getMatchedMiddleware()`.
43+
- Matched parameters, via `$result->getMatchedParams()` (as noted above, these
44+
are also each injected as discrete request attributes).
45+
- Allowed HTTP methods, via `$result->getAllowedMethods()`.
46+
47+
As an example, you could use middleware similar to the following to return a 403
48+
response if routing was successful, but no `Authorization` header is present:
49+
50+
```php
51+
use Zend\Diactoros\Response\EmptyResponse;
52+
use Zend\Expressive\Router\RouteResult;
53+
54+
function ($request, $response, $next) use ($routesRequiringAuthorization, $validator) {
55+
if (! ($result = $request->getAttribute(RouteResult::class, false))) {
56+
// No route matched; delegate to next middleware
57+
return $next($request, $response);
58+
}
59+
60+
if (! in_array($result->getMatchedRouteName(), $routesRequiringAuthorization, true)) {
61+
// Not a route requiring authorization
62+
return $next($request, $response);
63+
}
64+
65+
$header = $request->getHeaderLine('Authorization');
66+
if (! $validator($header)) {
67+
return new EmptyResponse(403);
68+
}
69+
70+
return $next($request, $response);
71+
}
72+
```
73+
74+
Note that the first step is to determine if we have a `RouteResult`; if we do
75+
not have one, we should either delegate to the next middleware, or return some
76+
sort of response (generally a 404). In the case of Expressive, a later
77+
middleware will generate the 404 response for us, so we can safely delegate.
78+
3479
## URI generation
3580

3681
Because routers have knowledge of the various paths they can match, they are

0 commit comments

Comments
 (0)