settings = $settings; } /** * Registers hooks. * * @return void */ public function register(): void { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Registers REST routes. * * @return void */ public function register_routes(): void { register_rest_route( self::ROUTE_NAMESPACE, '/settings', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_settings' ), 'permission_callback' => array( $this, 'can_manage' ), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_settings' ), 'permission_callback' => array( $this, 'can_manage' ), ), ) ); } /** * Only administrators may read or change settings. * * @return bool */ public function can_manage(): bool { return current_user_can( 'manage_options' ); } /** * Returns current settings. * * @return WP_REST_Response */ public function get_settings(): WP_REST_Response { return new WP_REST_Response( $this->settings->all() ); } /** * Saves settings from the request body. Unknown keys are dropped by Settings::sanitize(). * * @param WP_REST_Request $request Request. * @phpstan-param WP_REST_Request> $request * @return WP_REST_Response */ public function update_settings( WP_REST_Request $request ): WP_REST_Response { return new WP_REST_Response( $this->settings->update( $request->get_params() ) ); } }