AuuuhuuhuauhEUHAUEHAEHUAERFÆEFAEAEPRAAA!!!!!!1

AAAAAAAAAAAAALLLLALLAA
This commit is contained in:
William 2023-02-02 22:33:34 +00:00
parent 7be1668f00
commit e7c27c3770
1 changed files with 31 additions and 10 deletions

View File

@ -2,24 +2,33 @@
namespace WillySoft; namespace WillySoft;
abstract class Route { abstract class Route
static array $groups = [ {
static array $groups = [
[] []
]; ];
static function match(string $methods, string $path, callable $callback) { static string $prefix = '';
/**
* Check to see if the methods and path satisfy the request.
* and do some magic to retrieve the parameters before calling
* the callback passing those as arguments
*/
static function match(string $methods, string $path, callable $callback)
{
if (!in_array($_SERVER['REQUEST_METHOD'], if (!in_array($_SERVER['REQUEST_METHOD'],
array_map(strtoupper(...), explode('|', $methods)) array_map(strtoupper(...), explode('|', $methods))
)) return; )) return;
static $cache; static $request_path_parts_cache;
if (!isset($cache)) { if (!isset($request_path_parts_cache)) {
$cache = explode('/', urldecode( $request_path_parts_cache = explode('/', urldecode(
strtok($_SERVER['REQUEST_URI'], '?') strtok($_SERVER['REQUEST_URI'], '?')
)); ));
} }
$request_path_parts = $cache; $request_path_parts = $request_path_parts_cache;
$path_parts = explode('/', $path); $path_parts = explode('/', self::$prefix . $path);
$callback_args = []; $callback_args = [];
for ($i=0; $i < count($path_parts); $i++) { for ($i=0; $i < count($path_parts); $i++) {
if (empty($path_parts[$i])) { if (empty($path_parts[$i])) {
@ -61,7 +70,12 @@ abstract class Route {
static function form(string $path, callable $callback) { self::match('get|post', $path, $callback); } static function form(string $path, callable $callback) { self::match('get|post', $path, $callback); }
static function any(string $path, callable $callback) { self::match('get|post|put|patch|delete|options', $path, $callback); } static function any(string $path, callable $callback) { self::match('get|post|put|patch|delete|options', $path, $callback); }
static function middleware(callable|array $middlewares) { /**
* Require that a callable or an array of callables have to run
* if a route is matched within the current or all child groups
*/
static function middleware(callable|array $middlewares)
{
if (!is_array($middlewares)) { if (!is_array($middlewares)) {
$middlewares = [$middlewares]; $middlewares = [$middlewares];
} }
@ -72,9 +86,16 @@ abstract class Route {
} }
} }
static function group(callable $callback) {
static function group(string $prefix = '', ?callable $callback = null)
{
if (!str_starts_with($_SERVER['REQUEST_URI'], self::$prefix . $prefix)) {
return;
}
self::$prefix = self::$prefix . $prefix;
array_push(self::$groups, []); array_push(self::$groups, []);
$callback(); $callback();
array_pop(self::$groups); array_pop(self::$groups);
self::$prefix = rtrim(self::$prefix, $prefix);
} }
} }