From 1393e0face008325fbdeee6c05f93aa8ed40a4d1 Mon Sep 17 00:00:00 2001 From: Splashsky Date: Fri, 16 Jul 2021 07:06:37 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Build=20new=20prefix=20group=20t?= =?UTF-8?q?ype?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Splashsky/Router.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/Splashsky/Router.php b/src/Splashsky/Router.php index 0006039..f77b83c 100644 --- a/src/Splashsky/Router.php +++ b/src/Splashsky/Router.php @@ -9,6 +9,7 @@ class Router private static $pathNotFound; private static $methodNotAllowed; private static string $defaultConstraint = '([\w\-]+)'; + private static string $currentPrefix = ''; /** * A quick static function to register a route in the router. Used by the shorthand methods as well. @@ -20,6 +21,11 @@ class Router */ public static function add(string $route, callable|string $action, string|array $methods = 'GET') { + // If a prefix exists, prepend it to the route + if (!empty(self::$currentPrefix)) { + $route = self::$currentPrefix.$route; + } + self::$routes[] = [ 'route' => $route, 'action' => $action, @@ -96,6 +102,22 @@ class Router self::$defaultConstraint = $constraint; } + /** + * Accepts a callable that defines routes, and adds a prefix to them. + * + * @param string $prefix The prefix you want added to the routes. + * @param callable $routes A function that defines routes. + * @return void + */ + public static function prefix(string $prefix, callable $routes) + { + self::$currentPrefix = $prefix; + + $routes(); + + self::$currentPrefix = ''; + } + /** * Define a constraint for a route parameter. If only passing one parameter, * provide the parameter name as first argument and constraint as second. If