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