Gère davantage de cas dans le routeur

main
Clément FRÉVILLE 2 years ago
parent 9bc53b958f
commit 86827d1983

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Silex\Router;
final class PathHelper
{
public static function removeEverythingAfter(string $str, string $char): string
{
$pos = strpos($str, $char);
if ($pos !== false) {
return substr($str, 0, $pos);
}
return $str;
}
}

@ -19,16 +19,19 @@ class Router
public function __construct(string $url) public function __construct(string $url)
{ {
$this->url = trim($url, '/');; $url = PathHelper::removeEverythingAfter($url, '?');
$url = PathHelper::removeEverythingAfter($url, '#');
$this->url = trim($url, '/');
} }
public function setBasePath(string $basePath) public function setBasePath(string $basePath)
{ {
$pos = strpos($this->url, $basePath); $pos = strpos($this->url, $basePath);
if ($pos !== false) { if ($pos === false) {
$this->url = substr($this->url, $pos + strlen($basePath)); $this->url = null;
} else {
$this->url = trim(substr($this->url, $pos + strlen($basePath)), '/');
} }
var_dump($this->url);
} }
public function get(string $path, callable $callable): self public function get(string $path, callable $callable): self
@ -48,9 +51,11 @@ class Router
if (!isset($this->routes[$_SERVER['REQUEST_METHOD']])) { if (!isset($this->routes[$_SERVER['REQUEST_METHOD']])) {
throw new RouteNotFoundException('Unknown HTTP method'); throw new RouteNotFoundException('Unknown HTTP method');
} }
foreach ($this->routes[$_SERVER['REQUEST_METHOD']] as $route) { if ($this->url !== null) {
if ($route->matches($this->url)) { foreach ($this->routes[$_SERVER['REQUEST_METHOD']] as $route) {
return $route->call($di); if ($route->matches($this->url)) {
return $route->call($di);
}
} }
} }
throw new RouteNotFoundException('No matching routes'); throw new RouteNotFoundException('No matching routes');

Loading…
Cancel
Save