Skip to content

Commit

Permalink
fix #241
Browse files Browse the repository at this point in the history
  • Loading branch information
dannyvankooten committed Nov 23, 2019
1 parent a80bb36 commit 127f6e9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 7 additions & 2 deletions AltoRouter.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,8 @@ public function match($requestUrl = null, $requestMethod = null)
$requestUrl = substr($requestUrl, 0, $strpos);
}

$lastRequestUrlChar = $requestUrl[strlen($requestUrl)-1];

// set Request Method if it isn't passed as a parameter
if ($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
Expand All @@ -230,10 +232,12 @@ public function match($requestUrl = null, $requestMethod = null)
// No params in url, do string comparison
$match = strcmp($requestUrl, $route) === 0;
} else {
// Compare longest non-param string with url
if (strncmp($requestUrl, $route, $position) !== 0) {
// Compare longest non-param string with url before moving on to regex
// Check if last character before param is a slash, because it could be optional if param is optional too (see https://github.com/dannyvankooten/AltoRouter/issues/241)
if (strncmp($requestUrl, $route, $position) !== 0 && ($lastRequestUrlChar === '/' || $route[$position-1] !== '/')) {
continue;
}

$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params) === 1;
}
Expand All @@ -254,6 +258,7 @@ public function match($requestUrl = null, $requestMethod = null)
];
}
}

return false;
}

Expand Down
4 changes: 1 addition & 3 deletions tests/AltoRouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ public function testMatchWithPlainRoute()
->getMock();

// this should prove that compileRoute is not called when the route doesn't
// have any params in it, but this doesn't work because compileRoute is private.
// have any params in it
$router->expects($this->never())
->method('compileRoute');

Expand All @@ -384,8 +384,6 @@ public function testMatchWithPlainRoute()
'name' => 'contact'
], $router->match('/contact', 'GET'));

$router->map('GET', '/page/[:id]', 'pages#show', 'page');

// no prefix match, so no regex compilation necessary
$this->assertFalse($router->match('/page1', 'GET'));
}
Expand Down

0 comments on commit 127f6e9

Please sign in to comment.