repository = $repository; $this->schema = $schema; } public function register() { add_action( 'rest_api_init', array( $this, 'routes' ) ); } public function routes() { register_rest_route( 'artbees-quick-view/v1', '/settings', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get' ), 'permission_callback' => array( $this, 'permission' ) ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update' ), 'permission_callback' => array( $this, 'permission' ) ), ) ); register_rest_route( 'artbees-quick-view/v1', '/preview', array( 'methods' => 'POST', 'callback' => array( $this, 'preview' ), 'permission_callback' => array( $this, 'permission' ), ) ); } public function permission( $request ) { $nonce = $request->get_header( 'X-WP-Nonce' ); return current_user_can( 'manage_woocommerce' ) && is_string( $nonce ) && wp_verify_nonce( $nonce, 'wp_rest' ); } public function get() { return rest_ensure_response( array( 'settings' => $this->repository->get(), 'version' => (int) get_option( \artbees\QuickView\Storage\SettingsRepository::VERSION_OPTION, 0 ) ) ); } public function update( $request ) { $params = $request->get_json_params(); $settings = is_array( $params ) && isset( $params['settings'] ) && is_array( $params['settings'] ) ? $params['settings'] : array(); $expected = is_array( $params ) && isset( $params['version'] ) ? absint( $params['version'] ) : -1; $current = (int) get_option( \artbees\QuickView\Storage\SettingsRepository::VERSION_OPTION, 0 ); if ( $expected !== $current ) { return new \WP_Error( 'artbees_qv_settings_conflict', __( 'These settings changed in another tab. Reload the page and try again.', 'artbees-quick-view' ), array( 'status' => 409 ) ); } $validation = $this->schema->validate( $settings ); if ( ! $validation->is_valid() ) { return new \WP_Error( 'artbees_qv_invalid_settings', __( 'Check the highlighted settings and try again.', 'artbees-quick-view' ), array( 'status' => 400, 'errors' => $validation->errors() ) ); } if ( ! $this->repository->replace( $settings ) ) { return new \WP_Error( 'artbees_qv_settings_save_failed', __( 'Settings could not be saved. Your previous settings are still in place.', 'artbees-quick-view' ), array( 'status' => 500 ) ); } return $this->get(); } public function preview( $request ) { return \artbees\QuickView\Http\ProductController::preview_response( $request ); } }