Core\Router\Gate
The interface your class implements to control Core\Router::dispatch. You pass an instance of the class to dispatch, and it calls three methods:
| Method | When dispatch calls it | |---|---| | allows($route) | Before every route method. Return true to run the method. | | refused($reason, $route) | When no route method runs. $reason is a Core\Router\Refusal. | | failed($route, $error) | When the route method threw an error. The status is 500. |
When allows returns false or throws an error, the status is 403 and refused gets Refusal::Denied.
Every capture and #[Core\Query] value is converted before allows runs, and $route->parameter() returns it with its type. So allows can check a record that a parse method loaded.
dispatch sets the status before it calls refused or failed. Your method writes the body, and Core\Response::setStatus can change the status.
Good to know: an error in refused or failed is thrown again by dispatch. To send the value a route method returns, implement Core\Router\Responder. Otherwise nvs check gives a warning.
Examples
One gate for access and error pages
<?nvs// Shows a gate that checks each request and writes every error page of a small site.
use Core\Http\Method;use Core\Router\Refusal;
class Shop{ #[Core\Route(path: '/cart', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function cart(): void { echo 'your cart'; }
#[Core\Route(path: '/report', method: Core\Http\Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function report(): void { throw new RuntimeError('the report is not ready'); }}
class Gate implements Core\Router\Gate{ // `dispatch` calls this before each route method. Here every route is allowed. public function allows(Core\Router\Match $route): bool { return true; }
// The status is already set. This method changes a 404 to a 410. public function refused(Refusal $reason, ?Core\Router\Match $route): void { if ($reason == Refusal::NotFound) { Core\Response::setStatus(410); echo 'this page was removed'; } else { echo 'you cannot open this page'; } }
// The status is already 500. The visitor does not see the message of the error. public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'sorry, something went wrong'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // This prints `200 your cart`, then `410 this page was removed`, // then `500 sorry, something went wrong`. var $cart = Core\Test::request(Method::Get, '/cart'); echo $cart->status(), ' ', $cart->body(), "\n"; var $old = Core\Test::request(Method::Get, '/old-page'); echo $old->status(), ' ', $old->body(), "\n"; var $report = Core\Test::request(Method::Get, '/report'); echo $report->status(), ' ', $report->body(), "\n";}200 your cart410 this page was removed500 sorry, something went wrong