This commit is contained in:
xl
2023-06-12 15:31:46 +08:00
parent 418b470df3
commit c1e2655923
+21 -26
View File
@@ -38,10 +38,18 @@ class RouterCollector implements \ArrayAccess, \IteratorAggregate
*/
private HashMap $methods;
protected HashMap $default;
/**
* @throws ReflectionException
*/
public function __construct()
{
$this->methods = new HashMap();
$this->default = new HashMap();
$this->default->put('handler', new Handler([di(NotFoundController::class), 'fail'], []));
}
@@ -111,7 +119,7 @@ class RouterCollector implements \ArrayAccess, \IteratorAggregate
if (is_array($closure)) {
[$class, $method] = $closure;
} else {
if (!str_contains($closure,'@')) {
if (!str_contains($closure, '@')) {
$closure .= '@';
}
[$className, $method] = explode('@', $closure);
@@ -146,13 +154,13 @@ class RouterCollector implements \ArrayAccess, \IteratorAggregate
public function register(string $path, string $method, Handler $handler): void
{
$hashMap = HashMap::Tree($this->methods, $method);
foreach (str_split($path, 4) as $item) {
if ($hashMap->has($item)) {
$hashMap = $hashMap->get($item);
} else {
$hashMap->put($item, $hashMap = new HashMap());
}
}
// foreach (str_split($path, 4) as $item) {
// if ($hashMap->has($item)) {
// $hashMap = $hashMap->get($item);
// } else {
$hashMap->put($path, $hashMap = new HashMap());
// }
// }
$hashMap->put('handler', $handler);
$this->registerMiddleware($handler->getClass(), $handler->getMethod());
}
@@ -201,34 +209,21 @@ class RouterCollector implements \ArrayAccess, \IteratorAggregate
* @param string $path
* @param string $method
* @return Handler|null
* @throws ReflectionException
*/
public function query(string $path, string $method): ?Handler
{
if (!$this->methods->has($method)) {
return $this->NotFundHandler($path);
return $this->default->get('handler');
}
$parent = $this->methods->get($method);
foreach (str_split($path, 4) as $item) {
$parent = $parent->get($item);
if ($parent === null) {
return $this->NotFundHandler($path);
}
}
/** @var HashMap $parent */
$parent = $parent->get($path, $this->default);
return $parent->get('handler');
}
/**
* @param string $path
* @return Handler
* @throws ReflectionException
*/
private function NotFundHandler(string $path): Handler
{
return new Handler([di(NotFoundController::class), 'fail'], []);
}
/**
* @param string $route
* @return string