From 02177a67fa809b737e5509343b8a393ca0b84a25 Mon Sep 17 00:00:00 2001 From: BMTmohammedtaha Date: Sat, 14 Oct 2023 22:10:58 +0200 Subject: [PATCH] update getAction and matchRoutePattern method for accept any argement in pattern --- src/Exception/NotFoundException.php | 15 ++++++++++++++ src/Register.php | 31 +++++++++++++++++++---------- 2 files changed, 35 insertions(+), 11 deletions(-) create mode 100644 src/Exception/NotFoundException.php diff --git a/src/Exception/NotFoundException.php b/src/Exception/NotFoundException.php new file mode 100644 index 0000000..4c72a55 --- /dev/null +++ b/src/Exception/NotFoundException.php @@ -0,0 +1,15 @@ +remakeRoute($uri_path); $requestMethod = strtolower($method); - $length = $this->getLength($path); - - foreach ($this->routes as $route) { $fullPattern = $this->remakeRoute($route['pre_pattern'] . '/' . $route['pattern']); @@ -328,7 +331,10 @@ public function getAction(string $uri_path, string $method) if ($fullPattern === $path) { return $route; } - if (count($route['args']) !== 0 && $length === $route['length']) { + if ( + count($route['args']) !== 0 && + $this->getLength($path) === $this->getLength($fullPattern) + ) { if ($this->matchRoutePattern($path, $fullPattern)) { $args = $this->getArguments($path, $fullPattern); $route['args'] = $args; @@ -348,16 +354,19 @@ public function getAction(string $uri_path, string $method) * @param string $pattern The route pattern to match against. * @return bool True if the path matches the pattern, false otherwise. */ - public function matchRoutePattern($path, $pattern) + public function matchRoutePattern(string $path, string $pattern): bool { // Escape the special characters in the pattern $pattern = preg_quote($pattern, '/'); - // Replace "{id}" in the pattern with a regular expression to match any number - $pattern = str_replace('\{id\}', '(\d+)', $pattern); - - // Replace "{type}" in the pattern with a regular expression to match any word characters - $pattern = str_replace('\{type\}', '(\w+)', $pattern); + // Replace "{args}" in the pattern with a regular expression to match any number + foreach ($this->getSegmentFromPattern($pattern) as $arg) { + $pattern = str_replace( + sprintf('\{%s}', $arg), + $arg !== 'id' ? '(\w+)' : '(\d+)', + $pattern + ); + } // Perform the regex match if (preg_match('/^' . $pattern . '$/', $path, $matches)) {