Skip to content

Commit 1963562

Browse files
committed
fix: sometimes page not found change to not allowed.
1 parent b49a58b commit 1963562

File tree

12 files changed

+70
-71
lines changed

12 files changed

+70
-71
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"psr-4": {
2020
"Inhere\\Route\\" : "src/"
2121
},
22-
"files": ["src/functions.php"]
22+
"files": ["src/Helper/functions.php"]
2323
},
2424
"suggest": {
2525
"inhere/simple-print-tool": "Very lightweight data printing tools"

example/object.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,9 @@
6969

7070
$router->rest('/rest', RestController::class);
7171

72-
$router->any('*', function () {
73-
echo "This is fallback handler\n";
74-
});
72+
// $router->any('*', function () {
73+
// echo "This is fallback handler\n";
74+
// });
7575

7676
// var_dump($router);die;
7777

example/some-routes.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,11 @@ function my_handler(array $args) {
116116
'/user/login',
117117
'default_handler'
118118
],
119+
[
120+
['post'],
121+
'/admin/manage/getInfo[/id/{int}]',
122+
'default_handler'
123+
],
119124
/*
120125
match: /blog /saying
121126
*/

src/Base/AbstractRouter.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -385,14 +385,14 @@ public function validateArguments($methods, $handler): array
385385
throw new \InvalidArgumentException('The method and route handler is not allow empty.');
386386
}
387387

388-
$allow = self::ALLOWED_METHODS_STR . ',';
389388
$hasAny = false;
389+
$methods = \array_map(function ($m) use (&$hasAny) {
390+
$m = \strtoupper(\trim($m));
390391

391-
$methods = \array_map(function ($m) use ($allow, &$hasAny) {
392-
$m = \strtoupper(trim($m));
393-
394-
if (!$m || false === \strpos($allow, $m . ',')) {
395-
throw new \InvalidArgumentException("The method [$m] is not supported, Allow: " . trim($allow, ','));
392+
if (!$m || false === \strpos(self::ALLOWED_METHODS_STR . ',', $m . ',')) {
393+
throw new \InvalidArgumentException(
394+
"The method [$m] is not supported, Allow: " . self::ALLOWED_METHODS_STR
395+
);
396396
}
397397

398398
if (!$hasAny && $m === self::ANY) {

src/CachedRouter.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ final class CachedRouter extends ORouter
2828
* The routes cache file.
2929
* @var string
3030
*/
31-
protected $cacheFile;
31+
protected $cacheFile = '';
3232

3333
/**
3434
* Enable routes cache
@@ -170,7 +170,7 @@ public function setCacheEnable($cacheEnable)
170170
/**
171171
* @return string
172172
*/
173-
public function getCacheFile()
173+
public function getCacheFile(): string
174174
{
175175
return $this->cacheFile;
176176
}

src/Dispatcher/Dispatcher.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public function dispatch(int $status, string $path, array $info)
4040

4141
// method not allowed
4242
if ($status === RouterInterface::METHOD_NOT_ALLOWED) {
43+
unset($info['requestMethod']);
4344
return $this->handleNotAllowed($path, $method, $info);
4445
}
4546

@@ -79,13 +80,6 @@ public function dispatch(int $status, string $path, array $info)
7980

8081
// trigger route exec_end event
8182
$this->fire(self::ON_EXEC_END, [$path, $info]);
82-
} catch (\Exception $e) {
83-
// trigger route exec_error event
84-
if ($cb = $this->getOption(self::ON_EXEC_ERROR)) {
85-
return $this->fireCallback($cb, [$e, $path, $info]);
86-
}
87-
88-
throw $e;
8983
} catch (\Throwable $e) {
9084
// trigger route exec_error event
9185
if ($cb = $this->getOption(self::ON_EXEC_ERROR)) {
@@ -120,6 +114,7 @@ protected function validateMetadata(array $options)
120114
* @param $event
121115
* @param array $args
122116
* @return mixed
117+
* @throws \InvalidArgumentException
123118
*/
124119
protected function fire($event, array $args = [])
125120
{

src/Dispatcher/SimpleDispatcher.php

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ class SimpleDispatcher implements DispatcherInterface
2020
/** @var RouterInterface */
2121
private $router;
2222

23+
/** @var bool */
24+
private $initialized;
25+
2326
/**
2427
* some setting for self
2528
* @var array
@@ -53,9 +56,6 @@ class SimpleDispatcher implements DispatcherInterface
5356
// events
5457
];
5558

56-
/** @var bool */
57-
private $initialized;
58-
5959
/**
6060
* object creator.
6161
* @param RouterInterface $router
@@ -115,7 +115,7 @@ public function dispatchUri(string $path = null, string $method = null)
115115
{
116116
$path = $path ?: $_SERVER['REQUEST_URI'];
117117

118-
if (strpos($path, '?')) {
118+
if (\strpos($path, '?')) {
119119
$path = \parse_url($path, PHP_URL_PATH);
120120
}
121121

@@ -127,7 +127,6 @@ public function dispatchUri(string $path = null, string $method = null)
127127
$method = $method ?: $_SERVER['REQUEST_METHOD'];
128128

129129
list($status, $path, $info) = $this->router->match($path, $method);
130-
131130
$info['requestMethod'] = $method;
132131

133132
return $this->dispatch($status, $path, $info);
@@ -153,19 +152,21 @@ public function dispatch(int $status, string $path, array $info)
153152

154153
// method not allowed
155154
if ($status === RouterInterface::METHOD_NOT_ALLOWED) {
155+
unset($info['requestMethod']);
156156
return $this->handleNotAllowed($path, $method, $info);
157157
}
158158

159159
$result = null;
160160

161161
try {
162162
$result = $this->callRouteHandler($path, $method, $info['handler'], $args);
163-
} catch (\Exception $e) {
164-
$this->handleException($e, $path, $info);
165-
// throw new \RuntimeException($e->getMessage(), __LINE__, $e);
166163
} catch (\Throwable $e) {
167-
// throw new \RuntimeException($e->getMessage(), __LINE__, $e);
168-
$this->handleException($e, $path, $info);
164+
// trigger route exec_error event
165+
if ($cb = $this->getOption(self::ON_EXEC_ERROR)) {
166+
return $this->fireCallback($cb, [$e, $path, $info]);
167+
}
168+
169+
throw $e;
169170
}
170171

171172
return $result;
@@ -175,7 +176,7 @@ public function dispatch(int $status, string $path, array $info)
175176
* execute the matched Route Handler
176177
* @param string $path The route path
177178
* @param string $method The request method
178-
* @param callable $handler The route path handler
179+
* @param callable|mixed $handler The route path handler
179180
* @param array $args Matched param from path
180181
* [
181182
* 'matches' => []
@@ -235,7 +236,7 @@ protected function callRouteHandler(string $path, string $method, $handler, arra
235236
}
236237

237238
// action method is not exist
238-
if (!method_exists($controller, $actionMethod)) {
239+
if (!\method_exists($controller, $actionMethod)) {
239240
return $this->handleNotFound($path, $method, true);
240241
}
241242

@@ -288,7 +289,6 @@ protected function handleNotAllowed(string $path, string $method, array $methods
288289
// Run the 'NotAllowed' callback if the route was not found
289290
if (!$handler = $this->getOption(self::ON_METHOD_NOT_ALLOWED)) {
290291
$handler = $this->defaultNotAllowedHandler();
291-
292292
$this->setOption(self::ON_METHOD_NOT_ALLOWED, $handler);
293293

294294
// is a route path. like '/site/notFound'
@@ -308,25 +308,15 @@ protected function handleNotAllowed(string $path, string $method, array $methods
308308
return $this->fireCallback($handler, [$path, $method, $methods]);
309309
}
310310

311-
/**
312-
* @param \Exception|\Throwable $e
313-
* @param string $path
314-
* @param array $info
315-
*/
316-
public function handleException($e, string $path, array $info)
317-
{
318-
// handle ...
319-
}
320-
321311
/**
322312
* @return \Closure
323313
*/
324314
protected function defaultNotFoundHandler(): \Closure
325315
{
326316
return function ($path) {
327317
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
328-
header($protocol . ' 404 Not Found');
329-
echo "<h1 style='width: 60%; margin: 5% auto;'>:( 404<br>Page Not Found <code style='font-weight: normal;'>$path</code></h1>";
318+
\header($protocol . ' 404 Not Found');
319+
echo "<h1 style='width: 80%; margin: 5% auto; text-align: center;'>:( 404<br>Page Not Found <code style='font-weight: normal;'>$path</code></h1>";
330320
};
331321
}
332322

@@ -336,14 +326,15 @@ protected function defaultNotFoundHandler(): \Closure
336326
protected function defaultNotAllowedHandler(): \Closure
337327
{
338328
return function ($path, $method, $methods) {
339-
$allow = implode(',', $methods);
329+
$allow = \implode(',', $methods);
340330
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
341-
header($protocol . ' 405 Method Not Allowed');
331+
\header($protocol . ' 405 Method Not Allowed');
342332

343333
echo <<<HTML
344-
<div style="width: 500px; margin: 5% auto;">
345-
<h1>:( Method not allowed <code style="font-weight: normal;font-size: 16px">for $method $path</code></h1>
346-
<p style="font-size: 20px">Method not allowed. Must be one of: <strong>$allow</strong></p>
334+
<div style="min-width: 500px;margin: 5% auto;width: 80%;text-align: center;">
335+
<h1>:( Method not allowed </h1>
336+
<p style="font-size: 20px">Method not allowed for <strong>$method</strong> <code style="color: #d94141;font-size: smaller;">$path</code></p>
337+
<p>The request method must be one of <strong>$allow</strong></p>
347338
</div>
348339
HTML;
349340
};
@@ -362,13 +353,14 @@ public function on(string $event, $handler)
362353
}
363354

364355
/**
365-
* @param callable $cb
356+
* @param callable|mixed $cb
366357
* string - func name, class name
367358
* array - [class, method]
368359
* object - Closure, Object
369360
*
370361
* @param array $args
371362
* @return mixed
363+
* @throws \InvalidArgumentException
372364
*/
373365
protected function fireCallback($cb, array $args = [])
374366
{
File renamed without changes.

src/ORouter.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,11 @@ public function map($methods, string $route, $handler, array $opts = []): Abstra
7777

7878
/**
7979
* @param string $route
80-
* @param $handler
80+
* @param mixed $handler
8181
* @param array $opts
8282
* @return array
8383
*/
84-
protected function prepareForMap(string $route, $handler, array $opts)
84+
protected function prepareForMap(string $route, $handler, array $opts): array
8585
{
8686
if (!$this->initialized) {
8787
$this->initialized = true;
@@ -122,6 +122,7 @@ protected function prepareForMap(string $route, $handler, array $opts)
122122
* @param string $route
123123
* @param array $methods
124124
* @param array $conf
125+
* @throws \LogicException
125126
*/
126127
protected function collectParamRoute(string $route, array $methods, array $conf)
127128
{
@@ -310,7 +311,10 @@ protected function findInRegularRoutes(array $routesData, string $path, string $
310311
}
311312
}
312313

313-
return [self::NOT_FOUND, \explode(',', \trim($allowedMethods, ','))];
314+
return [
315+
self::NOT_FOUND,
316+
$allowedMethods ? \explode(',', \trim($allowedMethods, ',')) : []
317+
];
314318
}
315319

316320
/**
@@ -389,7 +393,7 @@ public function getGlobalOptions(): array
389393
* @param array $globalOptions
390394
* @return $this
391395
*/
392-
public function setGlobalOptions(array $globalOptions)
396+
public function setGlobalOptions(array $globalOptions): self
393397
{
394398
$this->globalOptions = $globalOptions;
395399

src/PreMatchRouter.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,15 @@ public function __construct(array $config = [], string $path = null, string $met
5858
public function setRequest(string $path = null, string $method = null)
5959
{
6060
if (!$path) {
61-
$path = $_SERVER['REQUEST_URI'] ?? '';
61+
$path = (string)($_SERVER['REQUEST_URI'] ?? '');
6262
}
6363

64-
if (strpos($path, '?')) {
64+
if (\strpos($path, '?')) {
6565
$path = \parse_url($path, PHP_URL_PATH);
6666
}
6767

6868
$this->reqPath = $this->formatUriPath($path, $this->ignoreLastSlash);
69-
$this->reqMethod = $method ? strtoupper($method) : $_SERVER['REQUEST_METHOD'];
69+
$this->reqMethod = $method ? \strtoupper($method) : $_SERVER['REQUEST_METHOD'];
7070
}
7171

7272
/**
@@ -102,7 +102,6 @@ public function map($methods, string $route, $handler, array $opts = []): Abstra
102102
$this->routeCounter++;
103103
// discard other routes data.
104104
// $this->staticRoutes = $this->regularRoutes = [];
105-
106105
return $this;
107106
}
108107

0 commit comments

Comments
 (0)