Skip to content

Commit

Permalink
Allow pattern for routing
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Mar 30, 2024
1 parent 0813ad6 commit 927d799
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/main/php/web/Routing.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ public function routes() { return $this->routes; }
* @return self
*/
public function matching($definitions, $target) {
static $quote= ['#' => '\\#'];

$handler= $target instanceof Handler ? $target : new Call($target);
foreach ((array)$definitions as $definition) {
if ('/' === $definition[0]) {
$this->routes['#^[A-Z]+ '.preg_quote(rtrim($definition, '/'), '#').'/#']= $handler;
$this->routes['#^[A-Z]+ '.strtr(rtrim($definition, '/'), $quote).'/#']= $handler;
} else {
sscanf($definition, "%[A-Z|] %[^\r]", $methods, $path);
$this->routes['#^'.$methods.' '.(null === $path ? '' : preg_quote(rtrim($path, '/'), '#')).'/#']= $handler;
$this->routes['#^'.$methods.' '.(null === $path ? '' : strtr(rtrim($path, '/'), $quote)).'/#']= $handler;
}
}
return $this;
Expand Down
9 changes: 9 additions & 0 deletions src/test/php/web/unittest/RoutingTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ public function matching_paths($url, $expected) {
);
}

#[Test, Values([['/test', 'specific'], ['/test.html', 'specific'], ['/', 'default']])]
public function matching_pattern($url, $expected) {
Assert::equals($this->handlers[$expected], (new Routing())
->matching('/test(.html)?', $this->handlers['specific'])
->fallbacks($this->handlers['default'])
->route(new Request(new TestInput('GET', $url)))
);
}

#[Test, Values(['/api', '//api', '///api', '/test/../api', '/./api', '/../api', '/./../api',])]
public function request_canonicalized_before_matching($requested) {
Assert::equals($this->handlers['specific'], Routing::cast(['/api' => $this->handlers['specific']])
Expand Down

0 comments on commit 927d799

Please sign in to comment.