PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.4
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.4
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 / V2 / Variations_Controller.php

Variations_Controller.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.4, at includes/API/V2/Variations_Controller.php

633 lines 26.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WCPOS sync read surface.
4 *
5 * @package WCPOS\WooCommercePOS\API\V2
6 */
7
8 namespace WCPOS\WooCommercePOS\API\V2;
9
10 use WC_Product_Variation;
11 use WC_REST_Product_Variations_Controller;
12 use WCPOS\WooCommercePOS\Services\Barcode_Field;
13 use WCPOS\WooCommercePOS\Sync\Api;
14 use WCPOS\WooCommercePOS\Sync\Collection_Rules;
15 use WCPOS\WooCommercePOS\Sync\Collection_Rules_Plan;
16 use WCPOS\WooCommercePOS\Sync\Digest_Index;
17 use WCPOS\WooCommercePOS\Sync\Endpoint_Permissions;
18 use WCPOS\WooCommercePOS\Sync\Pos_Visibility;
19 use WCPOS\WooCommercePOS\Sync\Product_Serializer;
20 use WP_Error;
21 use WP_Query;
22 use WP_REST_Request;
23 use WP_REST_Response;
24 use WP_REST_Server;
25
26 // phpcs:disable Squiz.Commenting, Generic.Commenting -- Ported lab documentation is preserved verbatim.
27
28 /**
29 * Variations document endpoint — the collection's hydration AND list/seed lane (ADR 0034).
30 *
31 * Why a flat route: the change-signal yields BARE variation ids (no parent), and WooCommerce's
32 * only variation routes are parent-mediated (`products/<parent>/variations`). One flat route
33 * IS the cross-parent collection: bare pages seed the complete replica (the idle trickle),
34 * `include=` is one filter on it (targeted hydration, no parent->child dance), and the
35 * SKU/barcode discovery search is another.
36 *
37 * Why it EXTENDS WooCommerce's variations controller: because that is all the route ever needed.
38 * WooCommerce's `get_objects()` already answers a cross-parent query — with no `product_id` in
39 * the route there is no parent constraint, and `include`/`search`/`orderby`/pagination are its
40 * own collection params. 1.9.x did exactly this: `parent::get_items( $request )`, one line
41 * (`API\V1\Product_Variations_Controller::wcpos_get_all_items`).
42 *
43 * The previous version of this class extended a bare `WP_REST_Controller` and rebuilt the query
44 * by hand — ~90 lines of raw postmeta SQL, five hand-declared args, no item schema — on the
45 * stated grounds that "wc/v3 has no cross-parent variations?include=". That claim was false, and
46 * the cost of acting on it was the payload: a variation hydrated through the PRODUCTS controller
47 * carries `images[]` instead of `image`, which blanked every variation thumbnail in the POS on
48 * 1.10.0 and wrote the parent's image onto every order line (#1710).
49 *
50 * What stays ours, and only this: the sync document envelope the engine reads
51 * (`documents[].{id,parent_id,payload,_rxdb_digest}`), POS visibility, the barcode carrier
52 * search, and the request bounds. Everything else is WooCommerce's.
53 */
54 class Variations_Controller extends WC_REST_Product_Variations_Controller {
55 /**
56 * Request keys the variation Collection Rules plan reads on this lane.
57 *
58 * @var array
59 */
60 private const WCPOS_SORT_PARAM_MAP = array(
61 'orderby' => 'orderby',
62 'order' => 'order',
63 );
64
65 /**
66 * The request whose declared sort `wcpos_posts_clauses()` applies.
67 *
68 * @var null|WP_REST_Request
69 */
70 private $wcpos_sort_request = null;
71
72 use Endpoint_Permissions;
73
74 private const MAX_SKU_LENGTH = 4096;
75 private const MAX_SKU_TERMS = 100;
76 private const MAX_SEARCH_LENGTH = 256;
77 private const MAX_SEARCH_TERMS = 10;
78 private const MAX_PAGE = 1000;
79
80
81 public function register_routes(): void {
82 /*
83 * ONLY the flat sync route. `parent::register_routes()` is deliberately not called: the
84 * v2 namespace is a read/sync surface, and writes ride Write_Controller, which already
85 * pushes through WooCommerce's nested routes. Registering WC's CRUD routes here would
86 * widen the POS-marker-gated surface for no consumer.
87 *
88 * The args and the schema are WooCommerce's own, so `include`, `search`, `orderby`,
89 * `order`, `offset`, `page`, `per_page`, `status` … all behave exactly as they do on
90 * wc/v3, and the route documents itself in the REST index.
91 */
92 register_rest_route(
93 Api::ROUTE_NAMESPACE,
94 '/variations',
95 array(
96 array(
97 'methods' => WP_REST_Server::READABLE,
98 'callback' => array( $this, 'get_variations' ),
99 'permission_callback' => array( $this, 'permissions_check' ),
100 'args' => $this->get_collection_params(),
101 ),
102 'schema' => array( $this, 'get_public_item_schema' ),
103 )
104 );
105 }
106
107 /**
108 * Narrow WooCommerce's variation query to what the POS may serve.
109 *
110 * Everything WooCommerce already understands — `include`, `offset`, `order`, pagination,
111 * status — comes from `parent::prepare_objects_query()`, which also applies
112 * `woocommerce_rest_product_variation_object_query` internally (wc/v3's CRUD controller fires
113 * it there, not in `get_items()`), so third-party query scoping reaches every lane built
114 * through this method. Layered on top — deliberately AFTER that filter, so a third party
115 * cannot widen what the POS may serve: POS visibility, the
116 * barcode-carrier search, and the sort keys the POS grids offer. This is the seam 1.9.x used
117 * for the same job (`API\V1\Product_Variations_Controller::prepare_objects_query`).
118 *
119 * @param WP_REST_Request $request Full details about the request.
120 *
121 * @return array
122 */
123 protected function prepare_objects_query( $request ) {
124 /*
125 * WooCommerce splits `sku` on commas without trimming, so `sku=A, B` looks for " B".
126 * Normalize before it sees the param rather than reimplementing its matching.
127 */
128 $sku = (string) ( $request->get_param( 'sku' ) ?? '' );
129 if ( '' !== $sku ) {
130 $terms = array_values(
131 array_filter(
132 array_map( 'trim', explode( ',', $sku ) ),
133 static function ( string $term ): bool {
134 return '' !== $term;
135 }
136 )
137 );
138 $sku = implode( ',', $terms );
139 $request->set_param( 'sku', $sku );
140 }
141
142 $args = parent::prepare_objects_query( $request );
143
144 /*
145 * A product is not a variation document.
146 *
147 * WooCommerce widens `post_type` to `array( 'product', 'product_variation' )` whenever
148 * `sku` is set, because the two share one SKU space. On THIS route that would serve a
149 * simple product as a variation — and the client would file it into its variations
150 * collection, the mirror image of the misfiled-variation pollution it already carries a
151 * one-shot repair for. Type purity on a variations route is ours to enforce.
152 */
153 $args['post_type'] = $this->post_type;
154
155 /*
156 * `search` means the barcode CARRIERS here, not the post title.
157 *
158 * WooCommerce maps `search` onto `s`, which searches post_title/content — useless for a
159 * variation, whose title is a generated attribute string. The POS searches what a cashier
160 * actually types or scans: the SKU and whichever meta key the store configured as its
161 * barcode field (`Barcode_Field::search_keys()`). Any term matching any carrier wins,
162 * which is the semantics the previous hand-rolled SQL had and the specs pin.
163 *
164 * `sku` is left to WooCommerce: its own exact/comma-list handling is what the
165 * sku-beats-search precedence rule relies on.
166 */
167 $search = (string) ( $request->get_param( 'search' ) ?? '' );
168 if ( '' !== $sku ) {
169 // SKU is an exact lookup and outranks a fuzzy one; leaving WooCommerce's post-title
170 // `s` in place would AND the two and return nothing.
171 unset( $args['s'] );
172 }
173 if ( '' !== $search && '' === $sku ) {
174 unset( $args['s'] );
175 $args['wcpos_variation_search'] = true;
176 $carriers = array( 'relation' => 'OR' );
177 foreach ( (array) preg_split( '/\s+/', trim( $search ), -1, PREG_SPLIT_NO_EMPTY ) as $term ) {
178 foreach ( Barcode_Field::search_keys() as $key ) {
179 $carriers[] = array(
180 'key' => $key,
181 'value' => $term,
182 'compare' => 'LIKE',
183 );
184 }
185 }
186 if ( 1 < \count( $carriers ) ) {
187 $args['meta_query'] = $this->add_meta_query( $args, $carriers ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
188 }
189 }
190
191 /*
192 * This route only ever offers what the store owner has for sale — on EVERY lane, including
193 * `include`.
194 *
195 * WooCommerce's Enabled checkbox on the variation metabox writes `post_status = private`
196 * when unchecked ({@see \WC_Meta_Box_Product_Data::save_variations()}), and WooCommerce
197 * honours that everywhere a customer can reach: `get_visible_children()` and
198 * `get_available_variations()` both drop it. A cashier must not be able to sell a variation
199 * the owner switched off, so the POS behaves the same way.
200 *
201 * The `include` lane is NOT exempt. Being asked for an id by name is not evidence the owner
202 * wants it sold: the client learns those ids from the parent's `variations[]`, which
203 * WooCommerce fills from `get_children()` — publish AND private — and from the change
204 * signal, which journals a disabled variation like any other post. A disabled id simply is
205 * not hydrated, the client's targeted-pull shortfall prunes it, and it leaves every till.
206 * Re-enabling saves the variation, which journals it, and it comes back.
207 *
208 * Set after `parent::prepare_objects_query()` so an explicit `status` param cannot widen it.
209 */
210 $args['post_status'] = 'publish';
211
212 /*
213 * Leg-3 (ADR 0014 WP-M5): POS-hidden (`online_only`) variations are never served. As a
214 * query exclusion rather than a post-hoc filter of the result, so paging and totals count
215 * the same set the client is allowed to see.
216 *
217 * Through the helper, NOT a raw `post__not_in` merge: `parent::prepare_objects_query()`
218 * maps `include` to `post__in`, and WP_Query IGNORES `post__not_in` when `post__in` is
219 * present — so `?search=X&include=<hidden id>` would have served a hidden variation.
220 * `apply_to_wp_query_args()` already owns that trap: it intersects `post__in` with the
221 * hidden set and pins an empty intersection to `array( 0 )`.
222 */
223 $args = ( new Pos_Visibility() )->apply_to_wp_query_args( $args, Pos_Visibility::VARIATIONS );
224
225 /*
226 * The POS sorts on fields WooCommerce does not offer as orderby values. They are
227 * declared in Sync\Collection_Rules and projected into get_collection_params()
228 * below — without that, `orderby=sku` is rejected by REST argument validation
229 * before anything here runs.
230 *
231 * They are applied as SQL clauses, NOT as `meta_key` + `orderby => meta_value`:
232 * that pair INNER JOINs postmeta and drops every variation with no value for the
233 * key, so the sort silently filtered. `wcpos_posts_clauses()` LEFT JOINs instead
234 * and orders the meta-less rows last.
235 */
236 $this->wcpos_sort_request = $request;
237 add_filter( 'posts_clauses', array( $this, 'wcpos_posts_clauses' ), 10, 2 );
238
239 return $args;
240 }
241
242 /**
243 * GET /variations — the flat collection's three lanes, one response shape.
244 *
245 * `?sku=`/`?search=` discovers by barcode carrier; a bare request serves one
246 * collection page (the trickle's seed lane); `?include=12,34` hydrates the
247 * named ids. All three resolve ids through WooCommerce's collection query,
248 * then hydrate through the shared assembly line below. Mirrors the wc/v3
249 * `products?include=` shape; the parent is resolved server-side off the
250 * loaded variation object (get_parent_id), so the client never needs to know
251 * parents. Unknown / non-variation ids are skipped (deletes are handled by
252 * the change-signal tombstone path, not here).
253 */
254 public function get_variations( WP_REST_Request $request ) {
255 $started = microtime( true );
256 $search_meta = null;
257 if ( $request->has_param( 'sku' ) || $request->has_param( 'search' ) ) {
258 $validation = $this->validate_search_request( $request );
259 if ( is_wp_error( $validation ) ) {
260 return $validation;
261 }
262 list( $ids, $search_meta ) = $this->search_variation_ids( $request );
263 } elseif ( array() === array_filter( (array) $request->get_param( 'include' ) ) ) {
264 /*
265 * A bare collection request — no `include`, no discovery term — answers page one of the
266 * POS-servable set with WooCommerce's own pagination, exactly as its `get_items()` would.
267 *
268 * This used to be a 400. That refusal is why the client still counts variations on the
269 * FROZEN `wcpos/v1` lane — the single remaining v1 call in the app — because the census
270 * probes a collection route and reads `X-WP-Total`, and no v2 variations route could
271 * answer "how many". Refusing the question was never a safety property: `include` is a
272 * filter, and a collection route with no filter is a collection.
273 */
274 list( $ids, $search_meta ) = $this->collection_page( $request );
275 } else {
276 /*
277 * The ask runs through the SAME query WooCommerce's own collection read builds
278 * (#1751): `parent::prepare_objects_query()` maps `include` to `post__in` and — in
279 * wc/v3's CRUD controller — applies `woocommerce_rest_product_variation_object_query`
280 * internally, so third-party query scoping reaches this lane like every other
281 * (hook-parity contract #1738). The collection and discovery lanes always had that
282 * property; this lane loaded ids directly and bypassed it. POS visibility and the
283 * publish gate ride the same args (layered in our override).
284 *
285 * The paging/ordering params are PINNED, not honoured: this lane answers a named
286 * ask, so `per_page` covers the whole ask, `offset`/`page` cannot skip any of it
287 * (a skipped id is absent from documents, which the client reads as "prune this
288 * id"), and `orderby=include` keeps WooCommerce from ordering by a meta key whose
289 * EXISTS join would silently drop every variation lacking that meta row. Pinning
290 * `orderby` also keeps the args complete for direct (non-dispatched) invocations,
291 * which carry no route defaults. Served order is the include order either way —
292 * the intersect below is the final authority.
293 */
294 $include_ids = array_values( array_unique( array_map( 'intval', (array) $request->get_param( 'include' ) ) ) );
295 // Pins live on a QUERY-ONLY clone: the dispatched request stays exactly
296 // as the client sent it, for the serializer's prepare-filters and for
297 // anything downstream reading it after dispatch.
298 $query_request = clone $request;
299 $query_request->set_param( 'per_page', max( 1, count( $include_ids ) ) );
300 $query_request->set_param( 'page', 1 );
301 $query_request->set_param( 'offset', 0 );
302 $query_request->set_param( 'orderby', 'include' );
303 $query_request->set_param( 'order', 'asc' );
304 $args = $this->prepare_objects_query( $query_request );
305
306 /*
307 * The ask is a CEILING. WooCommerce's variations controller UNIONS some
308 * collection params into `post__in` (`on_sale=true` array-unions every on-sale
309 * id on top of the ask), so without this intersection a stray param would
310 * hydrate the whole store into the till. No request param or filter may widen
311 * the served set beyond the named ids — narrowing is fine, that is what the
312 * object_query filter and the visibility exclusion are for. An emptied ask pins
313 * to `array( 0 )`, the same never-matches sentinel Pos_Visibility uses.
314 */
315 $post_in = array_values( array_intersect( array_map( 'intval', (array) ( $args['post__in'] ?? array() ) ), $include_ids ) );
316 $args['post__in'] = array() === $post_in ? array( 0 ) : $post_in;
317 $results = $this->get_objects( $args );
318
319 $allowed_ids = array();
320 foreach ( $results['objects'] as $object ) {
321 if ( $object instanceof WC_Product_Variation ) {
322 $allowed_ids[] = $object->get_id();
323 }
324 }
325 $ids = array_values( array_intersect( $include_ids, $allowed_ids ) );
326 }
327 _prime_post_caches( $ids, true, true );
328
329 // Hydrate through THE product assembly line (Product_Serializer), the same
330 // seam resolve/changes use (ADR 0003 — values come from the REST
331 // representation, never raw SQL). wc_get_product() returns a
332 // WC_Product_Variation for a variation id; the instanceof guard keeps a
333 // product id from being hydrated through this lane.
334 // Leg-3 (ADR 0014): attach each variation's stored 64-bit digest as `_rxdb_digest` so the client
335 // seeds its existence-reconcile manifest from this pull too (products get theirs via the proxy
336 // filter). Bulk-read once for the whole include set. A string — the digest exceeds int range.
337 // ::class, never the bare string: from inside this namespace
338 // class_exists( 'Digest_Index' ) probes the GLOBAL namespace and is
339 // forever false, so variation digests would never emit (review finding 3).
340 // Variations read the PRODUCTS id-space — one registry row owns both
341 // object types, so this lane cannot drift from the proxy lane's answer.
342 $digests = class_exists( Digest_Index::class )
343 ? ( new Digest_Index() )->read_digests( 'products', $ids )
344 : array();
345
346 $serializer = new Product_Serializer();
347 // A CLONE of the live request, not a synthetic bare one (so prepare-filters
348 // see the real request context), and not the live request itself (the
349 // serializer stamps store scope and a per-variation `product_id` onto
350 // whatever it is handed; the dispatched request must leave this method as
351 // the client sent it).
352 $serialization_request = clone $request;
353 $documents = array();
354 foreach ( $ids as $id ) {
355 $variation = wc_get_product( $id );
356 if ( ! $variation instanceof WC_Product_Variation ) {
357 continue;
358 }
359 /*
360 * DISABLED variations are never hydrated — see the `post_status` note in
361 * prepare_objects_query(). The query-level publish gate covers ALL lanes, including
362 * `include`; this check only guards a status change between the id query and object load.
363 *
364 * `meta.requested` now counts the query-eligible ask: a disabled or query-filtered id is
365 * absent from $ids. The client's targeted-pull shortfall — absence from documents — is
366 * unchanged.
367 */
368 if ( 'publish' !== $variation->get_status() ) {
369 continue;
370 }
371 $payload = $serializer->serialize( $variation, $serialization_request );
372 $document = array(
373 'id' => $id,
374 'parent_id' => (int) $variation->get_parent_id(),
375 'payload' => $payload,
376 );
377 if ( isset( $digests[ $id ] ) ) {
378 $document['_rxdb_digest'] = $digests[ $id ];
379 }
380 $documents[] = $document;
381 }
382
383 $meta = array(
384 'duration_ms' => round( ( microtime( true ) - $started ) * 1000, 3 ),
385 'requested' => \count( $ids ),
386 'returned' => \count( $documents ),
387 );
388 if ( null !== $search_meta ) {
389 $meta = array_merge( $meta, $search_meta );
390 }
391
392 $response = rest_ensure_response(
393 array(
394 'documents' => $documents,
395 'meta' => $meta,
396 )
397 );
398
399 /*
400 * The pagination WooCommerce would have sent.
401 *
402 * No v2 route emitted `X-WP-Total`/`X-WP-TotalPages` — including this one, the only one
403 * that paginates. The client asks for them on every v2 GET (the response envelope mirrors
404 * them into the body), so it has been receiving an empty mirror and falling back to
405 * short-page detection, which cannot tell "last page" from "the server truncated".
406 */
407 if ( null !== $search_meta && $response instanceof WP_REST_Response ) {
408 $response->header( 'X-WP-Total', (string) $search_meta['total'] );
409 $response->header(
410 'X-WP-TotalPages',
411 (string) ( $search_meta['per_page'] > 0 ? (int) ceil( $search_meta['total'] / $search_meta['per_page'] ) : 0 )
412 );
413 }
414
415 return $response;
416 }
417
418 /**
419 * Reject search requests that could build excessively large SQL queries or offsets.
420 *
421 * @return true|WP_Error
422 */
423 private function validate_search_request( WP_REST_Request $request ) {
424 $sku = (string) ( $request->get_param( 'sku' ) ?? '' );
425 $skus = array_filter(
426 array_map( 'trim', explode( ',', $sku ) ),
427 static function ( string $term ): bool {
428 return '' !== $term;
429 }
430 );
431 if ( array() !== $skus ) {
432 $sku = implode( ',', $skus );
433 if ( self::MAX_SKU_LENGTH < \strlen( $sku ) ) {
434 return new WP_Error( 'woocommerce_pos_variations_search_limit_exceeded', 'sku must not exceed 4096 bytes', array( 'status' => 400 ) );
435 }
436 if ( self::MAX_SKU_TERMS < \count( $skus ) ) {
437 return new WP_Error( 'woocommerce_pos_variations_search_limit_exceeded', 'sku must not contain more than 100 comma-separated terms', array( 'status' => 400 ) );
438 }
439 } else {
440 $search = (string) $request->get_param( 'search' );
441 if ( self::MAX_SEARCH_LENGTH < \strlen( $search ) ) {
442 return new WP_Error( 'woocommerce_pos_variations_search_limit_exceeded', 'search must not exceed 256 bytes', array( 'status' => 400 ) );
443 }
444 $terms = (array) preg_split( '/\s+/', trim( $search ), -1, PREG_SPLIT_NO_EMPTY );
445 if ( self::MAX_SEARCH_TERMS < \count( $terms ) ) {
446 return new WP_Error( 'woocommerce_pos_variations_search_limit_exceeded', 'search must not contain more than 10 whitespace-separated terms', array( 'status' => 400 ) );
447 }
448 }
449
450 if ( self::MAX_PAGE < (int) $request->get_param( 'page' ) ) {
451 return new WP_Error( 'woocommerce_pos_variations_search_limit_exceeded', 'page must not exceed 1000', array( 'status' => 400 ) );
452 }
453
454 return true;
455 }
456
457 /**
458 * Apply the declared POS variation sorts to the SQL clauses.
459 *
460 * `posts_clauses` fires for EVERY WP_Query, so the body is guarded by post type and by
461 * the plan itself — it contributes nothing unless this request claimed one of the
462 * declared sorts.
463 *
464 * @param array $clauses Associative array of the clauses for the query.
465 * @param WP_Query $wp_query The WP_Query instance.
466 *
467 * @return array
468 */
469 public function wcpos_posts_clauses( array $clauses, WP_Query $wp_query ): array {
470 if ( null === $this->wcpos_sort_request ) {
471 return $clauses;
472 }
473
474 $post_type = $wp_query->query_vars['post_type'] ?? null;
475 if ( 'product_variation' !== $post_type && ( ! \is_array( $post_type ) || ! \in_array( 'product_variation', $post_type, true ) ) ) {
476 return $clauses;
477 }
478
479 $plan = Collection_Rules::for_request( 'variations', $this->wcpos_sort_request, self::WCPOS_SORT_PARAM_MAP );
480
481 return $plan->filter( Collection_Rules_Plan::HOOK_POSTS_CLAUSES, $clauses, $wp_query );
482 }
483
484 /**
485 * WooCommerce's collection params, plus the sort keys the POS grids offer.
486 *
487 * `orderby` is a validated enum. Appending here is what lets `prepare_objects_query()` act on
488 * these four — otherwise the request 400s during argument validation and the switch is dead
489 * code. 1.9.x extended the same enum for the same reason.
490 */
491 public function get_collection_params() {
492 $params = parent::get_collection_params();
493
494 if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
495 $params['orderby']['enum'] = array_values(
496 array_unique(
497 array_merge(
498 $params['orderby']['enum'],
499 Collection_Rules::orderby_enum( 'variations' )
500 )
501 )
502 );
503 }
504
505 return $params;
506 }
507
508 /**
509 * De-duplicate variation searches joined through matching meta rows.
510 *
511 * @param string $groupby Existing GROUP BY clause.
512 * @param WP_Query $query Query being filtered.
513 */
514 public function group_search_results( string $groupby, WP_Query $query ): string {
515 global $wpdb;
516
517 return ! empty( $query->query_vars['wcpos_variation_search'] ) ? "{$wpdb->posts}.ID" : $groupby;
518 }
519
520 /**
521 * Does this discovery request still carry a term after normalization?
522 *
523 * `has_param()` is what selects discovery mode, and an empty or whitespace-only value passes
524 * it. This is the check that decides whether a query would actually be constrained.
525 */
526 private function has_discovery_constraint( WP_REST_Request $request ): bool {
527 $sku = (string) ( $request->get_param( 'sku' ) ?? '' );
528 if ( '' !== trim( $sku, " \t\n\r\0\x0B," ) ) {
529 return true;
530 }
531
532 $search = (string) ( $request->get_param( 'search' ) ?? '' );
533
534 return array() !== (array) preg_split( '/\s+/', trim( $search ), -1, PREG_SPLIT_NO_EMPTY );
535 }
536
537 /**
538 * One page of the POS-servable variation collection, with its total.
539 *
540 * WooCommerce's query pair, same as {@see search_variation_ids()} — the only difference is that
541 * a bare collection request carries no discovery constraint to normalize away, so the
542 * blank-scan guard that turns `?search=%20` into zero rows must NOT apply here. Visibility and
543 * `post_status` narrowing both ride `prepare_objects_query()`, so this page counts exactly what
544 * the client is allowed to receive.
545 *
546 * @return array{0: array<int, int>, 1: array{total: int, page: int, per_page: int}}
547 */
548 private function collection_page( WP_REST_Request $request ): array {
549 $per_page = max( 1, min( 100, (int) ( $request->get_param( 'per_page' ) ?? 10 ) ) );
550 $page = max( 1, (int) ( $request->get_param( 'page' ) ?? 1 ) );
551 $request->set_param( 'per_page', $per_page );
552 $request->set_param( 'page', $page );
553
554 $results = $this->get_objects( $this->prepare_objects_query( $request ) );
555
556 $ids = array();
557 foreach ( $results['objects'] as $object ) {
558 if ( $object instanceof WC_Product_Variation ) {
559 $ids[] = $object->get_id();
560 }
561 }
562
563 return array(
564 $ids,
565 array(
566 'total' => (int) ( $results['total'] ?? \count( $ids ) ),
567 'page' => $page,
568 'per_page' => $per_page,
569 ),
570 );
571 }
572
573 /**
574 * Discover a page of published, POS-visible variation ids by SKU/barcode.
575 *
576 * The query is WooCommerce's — `prepare_objects_query()` + `get_objects()`, the same pair its
577 * own `get_items()` uses. This method previously hand-built the SQL: a `wp_posts`/`wp_postmeta`
578 * INNER JOIN with `LIKE` predicates assembled per (field, term) pair, a second COUNT(DISTINCT)
579 * query for the total, and the hidden-id exclusion spliced into the same placeholder list. All
580 * of it duplicated `WP_Query` — which is where such copies go wrong, quietly and later.
581 *
582 * @return array{0: array<int, int>, 1: array{total: int, page: int, per_page: int}}
583 */
584 private function search_variation_ids( WP_REST_Request $request ): array {
585 $per_page = max( 1, min( 100, (int) ( $request->get_param( 'per_page' ) ?? 10 ) ) );
586 $page = max( 1, (int) ( $request->get_param( 'page' ) ?? 1 ) );
587 $request->set_param( 'per_page', $per_page );
588 $request->set_param( 'page', $page );
589
590 $query_args = $this->prepare_objects_query( $request );
591
592 /*
593 * A discovery request whose terms normalize away — `?sku=`, `?sku=,%20`, `?search=%20` —
594 * has no constraint left. Inherited, that query would return the FIRST PAGE OF EVERY
595 * VARIATION and advertise the catalogue-wide total; the replaced SQL deliberately used
596 * `1 = 0`. A blank scan must hydrate nothing, not everything.
597 */
598 if ( ! $this->has_discovery_constraint( $request ) ) {
599 return array(
600 array(),
601 array(
602 'total' => 0,
603 'page' => $page,
604 'per_page' => $per_page,
605 ),
606 );
607 }
608
609 add_filter( 'posts_groupby', array( $this, 'group_search_results' ), 10, 2 );
610 try {
611 $results = $this->get_objects( $query_args );
612 } finally {
613 remove_filter( 'posts_groupby', array( $this, 'group_search_results' ), 10 );
614 }
615
616 $ids = array();
617 foreach ( $results['objects'] as $object ) {
618 if ( $object instanceof WC_Product_Variation ) {
619 $ids[] = $object->get_id();
620 }
621 }
622
623 return array(
624 $ids,
625 array(
626 'total' => (int) ( $results['total'] ?? \count( $ids ) ),
627 'page' => $page,
628 'per_page' => $per_page,
629 ),
630 );
631 }
632 }
633