builder = $builder; $this->schema = $schema; $this->eligibility = $eligibility; self::$active = $this; } public static function preview_response( $request ) { return self::$active ? self::$active->preview( $request ) : new \WP_Error( 'artbees_qv_renderer_unavailable', __( 'Quick view is not available yet.', 'artbees-quick-view' ), array( 'status' => 503 ) ); } public function register() { add_action( 'rest_api_init', array( $this, 'routes' ) ); } public function routes() { register_rest_route( 'artbees-quick-view/v1', '/product/(?P\\d+)', array( 'methods' => 'GET', 'callback' => array( $this, 'product' ), 'permission_callback' => '__return_true', 'args' => array( 'id' => array( 'validate_callback' => static function( $value ) { return is_numeric( $value ) && (int) $value > 0; } ) ) ) ); } public function product( $request ) { return $this->response( (int) $request['id'] ); } public function preview( $request ) { $params = $request->get_json_params(); $id = is_array( $params ) ? absint( $params['product_id'] ?? 0 ) : 0; $settings = is_array( $params ) && is_array( $params['settings'] ?? null ) ? $params['settings'] : array(); if ( ! $this->schema->validate( $settings )->is_valid() ) { return new \WP_Error( 'artbees_qv_invalid_preview', __( 'Fix settings errors before previewing.', 'artbees-quick-view' ), array( 'status' => 400 ) ); } return $this->response( $id, $this->schema->normalize( $settings ), true ); } private function response( $id, array $settings = array(), $preview = false ) { if ( ! $preview && ! $this->eligibility->resolve( $id, new EligibilityContext( 'api' ) )->eligible() ) { return new \WP_Error( 'artbees_qv_product_unavailable', __( 'This product is no longer available.', 'artbees-quick-view' ), array( 'status' => 404 ) ); } try { $response = rest_ensure_response( $this->builder->build( $id, $settings, $preview ) ); do_action( 'artbees_qv/product/loaded', $response->get_data() ); $response->header( 'Cache-Control', 'no-store, max-age=0' ); return $response; } catch ( \RuntimeException $e ) { return new \WP_Error( 'artbees_qv_product_unavailable', __( 'This product is no longer available.', 'artbees-quick-view' ), array( 'status' => 404 ) ); } } }