Core\Router\Refusal
The reason Core\Router::dispatch did not call the method of a route.
dispatch sets the status and passes the reason to the refused method of your Core\Router\Gate. It writes the body and can change the status.
| Case | Status | When | |---|---|---| | NotFound | 404 | No route has this path. | | MethodNotAllowed | 405 | A route has this path, but not this HTTP method. | | UnknownMethod | 501 | The HTTP method is not a case of Core\Http\Method. | | Denied | 403 | allows() returned false or threw an error. | | Csrf | 403 | The CSRF token or the origin is not accepted. | | BodyTooLarge | 413 | The body is larger than the server's limit. | | BadCapture | 400 | A query value is not valid, or a required one is missing or repeated. Or a Parses class throws for a path value. |
A path value that is not a valid uint or Date gives NotFound.
route is null when no route matches.
To hide which ids exist, a gate sets 404 for both BadCapture and Denied.
Examples
A message for each reason
<?nvs// Shows a gate that writes a short message for each reason a route method did not run.use Core\Http\Method;use Core\Router\Refusal;
class Shop{ #[Core\Route(path: '/products/{id}', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function product(int $id): void { echo 'product ', $id; }
#[Core\Route(path: '/admin', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function admin(): void { echo 'admin page'; }}
class Gate implements Core\Router\Gate{ // This gate does not allow the admin page. public function allows(Core\Router\Match $route): bool { return !$route->is(Shop::admin); }
// `dispatch` already set the status for the reason. This method writes only the body. public function refused(Refusal $reason, ?Core\Router\Match $route): void { echo match ($reason) { Refusal::NotFound => 'This page does not exist.', Refusal::MethodNotAllowed => 'This page does not accept this method.', Refusal::BadCapture => 'This address is not valid.', Refusal::Denied, Refusal::Csrf => 'You cannot open this page.', Refusal::UnknownMethod, Refusal::BodyTooLarge => 'The request was not accepted.', }; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // This prints 200, 404, 405 and 403, each with its body. var $found = Core\Test::request(Method::Get, '/products/7'); echo $found->status(), ' ', $found->body(), "\n"; var $missing = Core\Test::request(Method::Get, '/basket'); echo $missing->status(), ' ', $missing->body(), "\n"; var $wrong = Core\Test::request(Method::Delete, '/products/7'); echo $wrong->status(), ' ', $wrong->body(), "\n"; var $denied = Core\Test::request(Method::Get, '/admin'); echo $denied->status(), ' ', $denied->body(), "\n";}200 product 7404 This page does not exist.405 This page does not accept this method.403 You cannot open this page.