diff --git a/src/App.php b/src/App.php index ce51b8c..13572bc 100644 --- a/src/App.php +++ b/src/App.php @@ -109,6 +109,15 @@ class App */ protected static $requestClass = ''; + /** + * @var bool + */ + protected static $methodNotAllowed = false; + /** + * @var string + */ + public static $allowedMethods = ''; + /** * App constructor. * @param string $requestClass @@ -154,9 +163,10 @@ public function onMessage($connection, $request) $plugin = $controllerAndAction['plugin'] ?? static::getPluginByPath($path); if (!$controllerAndAction || Route::hasDisableDefaultRoute($plugin)) { $request->plugin = $plugin; - $callback = static::getFallback($plugin); + $callback = static::$methodNotAllowed ? static::getMethodNotAllowedFallback($plugin) : static::getFallback($plugin); $request->app = $request->controller = $request->action = ''; static::send($connection, $callback($request), $request); + static::$methodNotAllowed = false; return null; } $app = $controllerAndAction['app']; @@ -238,6 +248,24 @@ protected static function getFallback(string $plugin = ''): Closure }; } + /** + * GetMethodNotAllowedFallback. + * @param string $plugin + * @return Closure + */ + protected static function getMethodNotAllowedFallback(string $plugin = ''): Closure + { + + return Route::getMethodNotAllowedFallback($plugin) ?: function () { + try { + $notFoundContent = file_get_contents(static::$publicPath . '/405.html'); + } catch (Throwable $e) { + $notFoundContent = '405 Method Not Allowed'; + } + return new Response(405, [], $notFoundContent); + }; + } + /** * ExceptionResponse. * @param Throwable $e @@ -560,6 +588,14 @@ protected static function findRoute(TcpConnection $connection, string $path, str static::send($connection, $callback($request), $request); return true; } + + if ( + $routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED and + count(array_diff($routeInfo[1], ['OPTIONS'])) > 0 + ){ + static::$methodNotAllowed = true; + static::$allowedMethods = implode(',' , $routeInfo[1] ?? []); + } return false; } diff --git a/src/Route.php b/src/Route.php index 87d7a70..cce7dee 100644 --- a/src/Route.php +++ b/src/Route.php @@ -61,6 +61,11 @@ class Route */ protected static $fallback = []; + /** + * @var null|callable + */ + protected static $methodNotAllowedFallback = []; + /** * @var array */ @@ -458,6 +463,27 @@ public static function getFallback(string $plugin = ''): ?callable return static::$fallback[$plugin] ?? null; } + /** + * methodNotAllowedFallback. + * @param callable|mixed $callback + * @param string $plugin + * @return void + */ + public static function methodNotAllowedFallback(callable $callback, string $plugin = '') + { + static::$methodNotAllowedFallback[$plugin] = $callback; + } + + /** + * GetMethodNotAllowedFallback. + * @param string $plugin + * @return callable|null + */ + public static function getMethodNotAllowedFallback(string $plugin = ''): ?callable + { + return static::$methodNotAllowedFallback[$plugin] ?? null; + } + /** * @return void * @deprecated