PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.19
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.19
1.10.19 1.10.18 1.10.17 1.10.16 1.10.15 1.10.13 1.10.14 1.10.12 1.10.11 1.10.10 1.10.9 1.10.8 untagged-3d9b7ccddc54df87c672 1.10.7 1.10.6 1.10.5 1.10.3 1.10.4 1.10.2 1.10.1 1.10.0 1.9.17 1.9.15 1.9.16 1.9.14 All 163 releases
woocommerce-pos / includes / API / V1 / Product_Variations_Controller.php

Product_Variations_Controller.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.19, at includes/API/V1/Product_Variations_Controller.php

493 lines 16.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Product_Variations_Controller.
4 *
5 * @package WCPOS\WooCommercePOS
6 */
7
8 namespace WCPOS\WooCommercePOS\API\V1;
9
10 \defined( 'ABSPATH' ) || die;
11
12 if ( ! class_exists( 'WC_REST_Product_Variations_Controller' ) ) {
13 return;
14 }
15
16 use Exception;
17 use WC_Data;
18 use WC_REST_Product_Variations_Controller;
19 use WCPOS\WooCommercePOS\Logger;
20 use WCPOS\WooCommercePOS\Services\Barcode_Field;
21 use WCPOS\WooCommercePOS\Sync\Collection_Rules;
22 use WCPOS\WooCommercePOS\Sync\Collection_Rules_Plan;
23 use WCPOS\WooCommercePOS\Sync\Pos_Visibility;
24 use WCPOS\WooCommercePOS\Sync\Product_Search;
25 use WP_Error;
26 use WP_Query;
27 use WP_REST_Request;
28 use WP_REST_Response;
29 use WP_REST_Server;
30
31 /**
32 * Product Tgas controller class.
33 *
34 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Product_Variations_Controller methods
35 */
36 class Product_Variations_Controller extends WC_REST_Product_Variations_Controller {
37 use Traits\Product_Helpers;
38 use Traits\Query_Helpers;
39 use Traits\Uuid_Handler;
40 use Traits\WCPOS_REST_API;
41
42 /**
43 * Endpoint namespace.
44 *
45 * @var string
46 */
47 protected $namespace = 'wcpos/v1';
48
49 /**
50 * Store the request object for use in lifecycle methods.
51 *
52 * Null until `wcpos_dispatch_request()` runs: the instance exists, and its filters are
53 * registered, before any request is assigned — which is why the readers guard with
54 * `isset()`. Matches the same property on `API\V1\Products_Controller`.
55 *
56 * @var null|WP_REST_Request
57 */
58 protected $wcpos_request;
59
60 /**
61 * Request keys the variation Collection Rules plan reads on this lane.
62 *
63 * @var array
64 */
65 private const WCPOS_SORT_PARAM_MAP = array(
66 'orderby' => 'orderby',
67 'order' => 'order',
68 'search' => 'search',
69 );
70
71 /**
72 * Dispatch request to parent controller, or override if needed.
73 *
74 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
75 * @param WP_REST_Request $request Request used to generate the response.
76 * @param string $route Route matched for the request.
77 * @param array $handler Route handler used for the request.
78 */
79 public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
80 $this->wcpos_request = $request;
81
82 add_filter( 'woocommerce_rest_prepare_product_variation_object', array( $this, 'wcpos_variation_response' ), 10, 3 );
83 add_action( 'woocommerce_rest_insert_product_variation_object', array( $this, 'wcpos_insert_product_variation_object' ), 10, 3 );
84 add_filter( 'woocommerce_rest_product_variation_object_query', array( $this, 'wcpos_product_variation_query' ), 10, 2 );
85
86 /*
87 * Check if the request is for all products and if the 'posts_per_page' is set to -1.
88 * Optimised query for getting all product IDs.
89 */
90 if ( Bulk_ID_Fast_Path::supports_request( $request ) ) {
91 return $this->wcpos_get_all_posts( $request );
92 }
93
94 return $dispatch_result;
95 }
96
97 /**
98 * Apply the collection's declared rules for nested and flat direct reads.
99 *
100 * @param WP_REST_Request $request Full details about the request.
101 * @return \WP_Error|\WP_REST_Response
102 */
103 public function get_items( $request ) {
104 $plan = Collection_Rules::for_request( 'variations', $request, self::WCPOS_SORT_PARAM_MAP );
105 return $plan->around(
106 function () use ( $request ) {
107 return parent::get_items( $request );
108 }
109 );
110 }
111
112 /**
113 * Register routes.
114 */
115 public function register_routes(): void {
116 parent::register_routes();
117
118 register_rest_route(
119 $this->namespace,
120 '/products/variations',
121 array(
122 array(
123 'methods' => WP_REST_Server::READABLE,
124 'callback' => array( $this, 'wcpos_get_all_items' ),
125 'permission_callback' => array( $this, 'get_items_permissions_check' ),
126 'args' => $this->get_collection_params(),
127 ),
128 'schema' => array( $this, 'get_public_item_schema' ),
129 )
130 );
131 }
132
133 /**
134 * Create a single variation.
135 *
136 * @param WP_REST_Request $request Full details about the request.
137 *
138 * @return WP_Error|WP_REST_Response
139 */
140 public function create_item( $request ) {
141 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
142 if ( is_wp_error( $invalid_meta ) ) {
143 return $invalid_meta;
144 }
145
146 return parent::create_item( $request );
147 }
148
149 /**
150 * Update a single variation.
151 *
152 * @param WP_REST_Request $request Full details about the request.
153 *
154 * @return WP_Error|WP_REST_Response
155 */
156 public function update_item( $request ) {
157 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
158 if ( is_wp_error( $invalid_meta ) ) {
159 return $invalid_meta;
160 }
161
162 return parent::update_item( $request );
163 }
164
165 /**
166 * Add custom fields to the product schema.
167 */
168 public function get_item_schema() {
169 $schema = parent::get_item_schema();
170
171 // Add the 'barcode' property if 'properties' exists and is an array.
172 if ( isset( $schema['properties'] ) && \is_array( $schema['properties'] ) ) {
173 $schema['properties']['barcode'] = array(
174 'description' => /* translators: REST API schema field label or error message. */ __( 'Barcode', 'woocommerce-pos' ),
175 'type' => 'string',
176 'context' => array( 'view', 'edit' ),
177 'readonly' => false,
178 );
179 }
180
181 // Check for 'stock_quantity' and allow decimal
182 // Note: 'number' is the valid JSON schema type for decimals (not 'float').
183 if ( $this->wcpos_allow_decimal_quantities() &&
184 isset( $schema['properties']['stock_quantity'] ) &&
185 \is_array( $schema['properties']['stock_quantity'] ) ) {
186 $schema['properties']['stock_quantity']['type'] = 'number';
187 }
188
189 return $schema;
190 }
191
192
193 /**
194 * Modify the collection params.
195 */
196 public function get_collection_params() {
197 $params = parent::get_collection_params();
198
199 // Check if 'per_page' parameter exists and has a 'minimum' key before modifying.
200 if ( isset( $params['per_page'] ) && \is_array( $params['per_page'] ) ) {
201 $params['per_page']['minimum'] = -1;
202 }
203
204 // Search text is literal on every lane: `sanitize_text_field` would strip `%30`
205 // and blank malformed UTF-8 before the declared search rule ever saw them.
206 if ( isset( $params['search'] ) && \is_array( $params['search'] ) ) {
207 $params['search']['sanitize_callback'] = 'rest_sanitize_request_arg';
208 }
209
210 // Ensure 'orderby' is set and is an array before attempting to modify it.
211 if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
212 // DECLARED once, in Sync\Collection_Rules, and projected here — so a sort cannot
213 // be advertised on one lane and rejected on the other.
214 $new_sort_options = Collection_Rules::orderby_enum( 'variations' );
215 $params['orderby']['enum'] = array_unique( array_merge( $params['orderby']['enum'], $new_sort_options ) );
216 }
217
218 return $params;
219 }
220
221 /**
222 * Filter the variation response.
223 *
224 * @param WP_REST_Response $response The response object.
225 * @param WC_Data $variation Product data.
226 * @param WP_REST_Request $request Request object.
227 *
228 * @return WP_REST_Response $response The response object.
229 */
230 public function wcpos_variation_response( WP_REST_Response $response, WC_Data $variation, WP_REST_Request $request ): WP_REST_Response {
231 $data = $response->get_data();
232
233 // Add the UUID to the product response.
234 $this->maybe_add_post_uuid( $variation );
235
236 // Add the barcode to the product response.
237 $data['barcode'] = $this->wcpos_get_barcode( $variation ); // @phpstan-ignore-line
238
239 // Check if the response has an image.
240 if ( isset( $data['image'] ) && ! empty( $data['image'] ) && isset( $data['image']['id'] ) ) {
241 // Replace the full size 'src' with the URL of the medium size image.
242 $medium_image_data = image_downsize( $data['image']['id'], 'medium' );
243
244 if ( $medium_image_data ) {
245 $data['image']['src'] = $medium_image_data[0];
246 }
247 }
248
249 /*
250 * Backwards compatibility for WooCommerce < 8.3
251 *
252 * WooCommerce added 'parent_id' and 'name' to the variation response in 8.3
253 */
254 if ( ! isset( $data['parent_id'] ) ) {
255 $data['parent_id'] = $variation->get_parent_id();
256 }
257 if ( ! isset( $data['name'] ) ) {
258 $data['name'] = \function_exists( 'wc_get_formatted_variation' ) ? wc_get_formatted_variation( $variation, true, false, false ) : ''; // @phpstan-ignore-line
259 }
260
261 // Parse the meta data before returning the response.
262 $data['meta_data'] = $this->wcpos_parse_meta_data( $variation );
263
264 // Estimate response size and log if excessive.
265 $this->wcpos_estimate_response_size( $data, $variation->get_id(), 'Variation' );
266
267 $response->set_data( $data );
268
269 return $response;
270 }
271
272 /**
273 * Fires after a single object is created or updated via the REST API.
274 *
275 * @param WC_Data $object Inserted object.
276 * @param WP_REST_Request $request Request object.
277 * @param bool $creating True when creating object, false when updating.
278 */
279 public function wcpos_insert_product_variation_object( WC_Data $object, WP_REST_Request $request, $creating ): void {
280 // Update the barcode if it is set in the request.
281 if ( $request->has_param( 'barcode' ) ) {
282 Barcode_Field::write( $object, $request->get_param( 'barcode' ) );
283 }
284 }
285
286 /**
287 * Filter to adjust the WordPress search SQL query
288 * - Search for the variation SKU and barcode
289 * - Do not search variation description.
290 *
291 * @param string $search Search string.
292 * @param WP_Query $wp_query WP_Query object.
293 *
294 * @return string
295 * @deprecated Collection Rules now installs this behavior.
296 */
297 public function wcpos_posts_search( string $search, WP_Query $wp_query ) {
298 return Product_Search::variation_posts_search( $search, $wp_query->query_vars, Collection_Rules::rules( 'variations' )['search'] );
299 }
300
301 /**
302 * Filters the JOIN clause of the query.
303 *
304 * @param string $join The JOIN clause of the query.
305 * @param WP_Query $query The WP_Query instance (passed by reference).
306 *
307 * @return string
308 * @deprecated Collection Rules now installs this behavior.
309 */
310 public function wcpos_posts_join_to_posts_search( string $join, WP_Query $query ) {
311 return empty( $query->query_vars['s'] ) ? $join : Product_Search::posts_join( $join, $query->query_vars );
312 }
313
314 /**
315 * Filters the GROUP BY clause of the query.
316 *
317 * @param string $groupby The GROUP BY clause of the query.
318 * @param WP_Query $query The WP_Query instance (passed by reference).
319 *
320 * @return string
321 * @deprecated Collection Rules now installs this behavior.
322 */
323 public function wcpos_posts_groupby_posts_search( string $groupby, WP_Query $query ) {
324 return empty( $query->query_vars['s'] ) ? $groupby : Product_Search::posts_groupby( $groupby, $query->query_vars );
325 }
326
327 /**
328 * Filter the query arguments for a request.
329 *
330 * @param array $args Key value array of query var to query value.
331 * @param WP_REST_Request $request The request used.
332 *
333 * @return array $args Key value array of query var to query value.
334 */
335 public function wcpos_product_variation_query( array $args, WP_REST_Request $request ) {
336 // Check for wcpos_include/wcpos_exclude parameter.
337 // The Collection Rules visibility backstop runs first, at priority 10.
338 if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
339 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_variation_include_exclude' ), 20, 2 );
340 }
341
342 return $args;
343 }
344
345 /**
346 * Filters the WHERE clause of the query.
347 *
348 * Exclusion set and feature gate both come from Sync\Pos_Visibility, the single POS visibility
349 * authority.
350 *
351 * @param string $where The WHERE clause of the query.
352 * @param WP_Query $query The WP_Query instance (passed by reference).
353 *
354 * @return string
355 * @deprecated Collection Rules now installs this behavior.
356 */
357 public function wcpos_posts_where_product_variation_exclude_online_only( string $where, WP_Query $query ) {
358 global $wpdb;
359
360 return ( new Pos_Visibility() )->apply_to_sql_where( $where, "{$wpdb->posts}.ID", Pos_Visibility::VARIATIONS );
361 }
362
363 /**
364 * Filters the WHERE clause of the query.
365 *
366 * @param string $where The WHERE clause of the query.
367 * @param WP_Query $query The WP_Query instance (passed by reference).
368 *
369 * @return string
370 */
371 public function wcpos_posts_where_product_variation_include_exclude( string $where, WP_Query $query ) {
372 global $wpdb;
373
374 // Handle 'wcpos_include'.
375 if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
376 $include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
377 $ids_format = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
378 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID IN ($ids_format) ", $include_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
379 }
380
381 // Handle 'wcpos_exclude'.
382 if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
383 $exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
384 $ids_format = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
385 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID NOT IN ($ids_format) ", $exclude_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
386 }
387
388 return $where;
389 }
390
391 /**
392 * Returns array of all product ids, name.
393 *
394 * @param WP_REST_Request $request Full details about the request.
395 *
396 * @return WP_Error|WP_REST_Response
397 */
398 public function wcpos_get_all_posts( $request ) {
399 global $wpdb;
400
401 $start_time = microtime( true );
402 $parent_id = (int) $this->wcpos_request->get_param( 'product_id' );
403 $select_fields = Bulk_ID_Fast_Path::select_fields( $request, 'ID', 'post_modified_gmt' );
404
405 // Initialize the SQL query.
406 $sql = "SELECT DISTINCT {$select_fields} FROM {$wpdb->posts}";
407 $sql .= " WHERE {$wpdb->posts}.post_type = 'product_variation' AND {$wpdb->posts}.post_status = 'publish'";
408
409 // Drop the POS-hidden ids — Sync\Pos_Visibility owns both the exclusion set and the feature gate.
410 $sql = ( new Pos_Visibility() )->apply_to_sql_where( $sql, 'ID', Pos_Visibility::VARIATIONS );
411
412 $modified_after_date = Bulk_ID_Fast_Path::modified_after_gmt( $request );
413 if ( $modified_after_date ) {
414 $sql .= $wpdb->prepare( ' AND post_modified_gmt > %s', $modified_after_date );
415 }
416
417 $sql = Bulk_ID_Fast_Path::append_id_filters_sql( $sql, $request, "{$wpdb->posts}.ID" );
418
419 // Dynamically add the post_parent clause if a parent ID is provided.
420 if ( $parent_id ) {
421 $sql .= $wpdb->prepare( " AND {$wpdb->posts}.post_parent = %d", $parent_id );
422 }
423
424 try {
425 $results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is built with prepare() above.
426
427 return Bulk_ID_Fast_Path::response( $this, $results, $start_time );
428 } catch ( Exception $e ) {
429 return Bulk_ID_Fast_Path::fetch_error( 'Error fetching product variation IDs: ' . $e->getMessage(), 'Error fetching product variation IDs.' );
430 }
431 }
432
433 /**
434 * Endpoint for getting all product variations, eg: search for sku or barcode.
435 *
436 * @param WP_REST_Request $request Full details about the request.
437 */
438 public function wcpos_get_all_items( $request ) {
439 return $this->get_items( $request );
440 }
441
442
443 /**
444 * Apply the declared POS variation sorts to the SQL clauses.
445 *
446 * `posts_clauses` fires for EVERY WP_Query, so the body is guarded by post type and by
447 * the plan itself — it contributes nothing unless this request claimed one of the
448 * declared sorts.
449 *
450 * @param array $clauses Associative array of the clauses for the query.
451 * @param WP_Query $wp_query The WP_Query instance.
452 *
453 * @return array
454 * @deprecated Collection Rules now installs this behavior.
455 */
456 public function wcpos_posts_clauses( array $clauses, WP_Query $wp_query ): array {
457 if ( ! isset( $this->wcpos_request ) ) {
458 return $clauses;
459 }
460
461 $post_type = $wp_query->query_vars['post_type'] ?? null;
462 if ( 'product_variation' !== $post_type && ( ! \is_array( $post_type ) || ! \in_array( 'product_variation', $post_type, true ) ) ) {
463 return $clauses;
464 }
465
466 $plan = Collection_Rules::for_request( 'variations', $this->wcpos_request, self::WCPOS_SORT_PARAM_MAP );
467
468 return $plan->filter( Collection_Rules_Plan::HOOK_POSTS_CLAUSES, $clauses, $wp_query );
469 }
470
471 /**
472 * Prepare objects query.
473 *
474 * @param WP_REST_Request $request Full details about the request.
475 *
476 * @return array|WP_Error
477 */
478 protected function prepare_objects_query( $request ) {
479 $args = parent::prepare_objects_query( $request );
480
481 /*
482 * The POS sorts (`sku`, `barcode`, `stock_quantity`, `stock_status`) are NOT mapped
483 * onto `meta_key` + `orderby => meta_value` here any more. That pair INNER JOINs
484 * postmeta, so it dropped every variation with no value for the key — a sort acting
485 * as a filter. `Sync\Collection_Rules` declares them and its scoped plan
486 * applies them as a LEFT JOIN, on this lane and on `wcpos/v2` alike.
487 */
488
489 $plan = Collection_Rules::for_request( 'variations', $request, self::WCPOS_SORT_PARAM_MAP );
490 return $plan->filter( Collection_Rules_Plan::HOOK_PREPARE_ARGS, $args );
491 }
492 }
493