Skip to content
Open
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,16 @@ $router->before('GET|POST', '/admin/.*', function() {

Unlike route handling functions, more than one before route middleware is executed when more than one route match is found.

If you want to run the same middleware for different routes you could try this
```php
$router->before('GET|POST', ['/admins/.*', '/helpers/.*'], function() {
$token = Request::get()->Header('Authorization');
if (!Auth::validate($token)) {
header('location: /error/forbidden');
exit;
}
});
```

### Before Router Middlewares

Expand Down
25 changes: 15 additions & 10 deletions src/Bramus/Router/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,24 @@ class Router
* Store a before middleware route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param string $pattern A route(s) pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function before($methods, $pattern, $fn)
public function before($methods, $patterns, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;

foreach (explode('|', $methods) as $method) {
$this->beforeRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
if (is_string($patterns)) {
$patterns = [$patterns];
}
foreach ($patterns as $pattern) {
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;

foreach (explode('|', $methods) as $method) {
$this->beforeRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
}

Expand Down