From 7f9a9beebb1fbbc5c5dd4cd73c16ce68e210f1b1 Mon Sep 17 00:00:00 2001 From: cstayyab Date: Thu, 3 Sep 2020 16:41:31 +0500 Subject: [PATCH 1/2] Implemented Arbitrary Parameters match from Path --- src/Application.php | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/Application.php b/src/Application.php index a22db75..9c3dd12 100644 --- a/src/Application.php +++ b/src/Application.php @@ -16,10 +16,7 @@ class Application protected $response; - protected $patterns = array( - ':id' => '(\d+)', - ':hash' => '([a-f\d+]{32})' - ); + protected $patterns = array(); public function __construct() { @@ -124,6 +121,20 @@ public function run() foreach ($this->router->getRoutes() as $route) { + $parts = explode('/', $route->getPath()); + $patterns = []; + $pattern = ""; + foreach($parts as $i=>$part) { + if(substr( $part, 0, 1 ) == ":") { + $patterns[$part] = $i; + $pattern .= "/" . "(\w+)"; + } else { + $pattern .= "/" . $part; + } + } + $pattern = "#^" . substr($pattern, 1) . "$#"; + $this->patterns = $patterns; + $match1 = in_array($route->getMethod(), array('all', 'use', strtolower($this->request->method))); if (!$match1) { @@ -132,7 +143,6 @@ public function run() $use = $route->getMethod() == "use"; - $pattern = sprintf("#^%s$#", str_replace(array_keys($this->patterns), array_values($this->patterns), $route->getPath())); if (!$use) { $match2 = null; @@ -141,7 +151,7 @@ public function run() continue; } else { array_shift($match2); - $this->setParams($match2); + $this->setParams(); } } else { if (!($route->getPath() == '*' || preg_match($pattern, $this->request->path))) @@ -165,19 +175,13 @@ public function run() } } - protected function setParams(array $match2): Application + protected function setParams(): Application { - foreach ($match2 as $match) - { - foreach ($this->patterns as $param => $pattern) + $parts = explode('/', $this->request->path); + foreach ($this->patterns as $param => $i) { - if (preg_match("#^$pattern$#", $match)) - { - $this->request->params[substr($param, 1)] = $match; - } + $this->request->params[substr($param, 1)] = $parts[$i]; } - } - return $this; } From d95cfbfa0a8516ef34a9fdffc9ca86356c5ba3df Mon Sep 17 00:00:00 2001 From: cstayyab Date: Thu, 3 Sep 2020 17:54:37 +0500 Subject: [PATCH 2/2] Fixed Regex to match all characters between " / "s --- src/Application.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Application.php b/src/Application.php index 9c3dd12..57ba5a5 100644 --- a/src/Application.php +++ b/src/Application.php @@ -127,7 +127,7 @@ public function run() foreach($parts as $i=>$part) { if(substr( $part, 0, 1 ) == ":") { $patterns[$part] = $i; - $pattern .= "/" . "(\w+)"; + $pattern .= "/" . "(.+)"; } else { $pattern .= "/" . $part; }