service = $service; } public function registerRoutes(): void { register_rest_route( 'intellilanz/v1', '/analysis', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => array( $this, 'getLatest' ), 'permission_callback' => array( $this, 'permissionsCheck' ) ) ); register_rest_route( 'intellilanz/v1', '/analysis/run', array( 'methods' => 'POST', 'callback' => array( $this, 'run' ), 'permission_callback' => array( $this, 'permissionsCheck' ) ) ); } public function permissionsCheck(): bool { return current_user_can( 'manage_options' ); } public function getLatest() { if ( ! $this->permissionsCheck() ) { return $this->forbidden(); } try { return $this->response( $this->service->latest() ); } catch ( \Throwable $error ) { return $this->failed(); } } public function run() { if ( ! $this->permissionsCheck() ) { return $this->forbidden(); } try { return $this->response( $this->service->run() ); } catch ( \Throwable $error ) { return $this->failed(); } } private function response( ?array $analysis ) { $response = new \WP_REST_Response( array( 'has_analysis' => $analysis !== null, 'analysis' => $analysis, 'history' => $this->service->history() ), 200 ); $response->header( 'Cache-Control', 'no-store, private' ); return $response; } private function forbidden(): \WP_Error { return new \WP_Error( 'intellilanz_forbidden', __( 'You cannot run this analysis.', 'intellilanz' ), array( 'status' => rest_authorization_required_code() ) ); } private function failed(): \WP_Error { return new \WP_Error( 'intellilanz_analysis_failed', __( 'The site analysis could not be completed.', 'intellilanz' ), array( 'status' => 500 ) ); } }