Skip to content

Commit

Permalink
update getAction and matchRoutePattern method for accept any argement…
Browse files Browse the repository at this point in the history
… in pattern
  • Loading branch information
BMTmohammedtaha committed Oct 14, 2023
1 parent bef93b8 commit 02177a6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
15 changes: 15 additions & 0 deletions src/Exception/NotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Effectra\Router\Exception;

use Exception;

/**
* Exception thrown when an not found correct route.
*/
class NotFoundException extends Exception
{

}
31 changes: 20 additions & 11 deletions src/Register.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,23 +312,29 @@ public function setExcludedPattern(string|array $pattern): void
}


public function getAction(string $uri_path, string $method)
/**
* get the correct route
* @param string $uri_path the uri path
* @param string $method the http method
* @return null|array the correct route for uri or null if not exists
*/
public function getAction(string $uri_path, string $method): ?array
{
$path = $this->remakeRoute($uri_path);

$requestMethod = strtolower($method);

$length = $this->getLength($path);


foreach ($this->routes as $route) {
$fullPattern = $this->remakeRoute($route['pre_pattern'] . '/' . $route['pattern']);

if ($requestMethod === $route['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;
Expand All @@ -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)) {
Expand Down

0 comments on commit 02177a6

Please sign in to comment.