diff --git a/README.md b/README.md index b0f61a5..f9dc76f 100755 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/Bramus/Router/Router.php b/src/Bramus/Router/Router.php index 43d7d7a..06d7de6 100644 --- a/src/Bramus/Router/Router.php +++ b/src/Bramus/Router/Router.php @@ -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, + ); + } } }