/var/www/html_us/wp-content/plugins/woocommerce/src/StoreApi/Utilities/CartController.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
<?php
namespace Automattic\WooCommerce\StoreApi\Utilities;

use 
Automattic\WooCommerce\Checkout\Helpers\ReserveStock;
use 
Automattic\WooCommerce\Enums\ProductStatus;
use 
Automattic\WooCommerce\Enums\ProductType;
use 
Automattic\WooCommerce\StoreApi\Exceptions\InvalidCartException;
use 
Automattic\WooCommerce\StoreApi\Exceptions\NotPurchasableException;
use 
Automattic\WooCommerce\StoreApi\Exceptions\OutOfStockException;
use 
Automattic\WooCommerce\StoreApi\Exceptions\PartialOutOfStockException;
use 
Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
use 
Automattic\WooCommerce\StoreApi\Exceptions\TooManyInCartException;
use 
Automattic\WooCommerce\StoreApi\Utilities\ArrayUtils;
use 
Automattic\WooCommerce\StoreApi\Utilities\DraftOrderTrait;
use 
Automattic\WooCommerce\StoreApi\Utilities\NoticeHandler;
use 
Automattic\WooCommerce\StoreApi\Utilities\QuantityLimits;
use 
WP_Error;

/**
 * Woo Cart Controller class.
 *
 * Helper class to bridge the gap between the cart API and Woo core.
 */
class CartController {
    use 
DraftOrderTrait;

    
/**
     * Makes the cart and sessions available to a route by loading them from core.
     */
    
public function load_cart() {
        if ( 
did_action'woocommerce_load_cart_from_session' ) ) {
            return;
        }

        
// Initialize the cart.
        
wc_load_cart();

        
// Load cart from session.
        
$cart $this->get_cart_instance();
        
$cart->get_cart();
    }

    
/**
     * Normalizes the cart by fixing any quantity violations.
     */
    
public function normalize_cart() {
        
$quantity_limits = new QuantityLimits();
        
$cart_items      $this->get_cart_items();

        foreach ( 
$cart_items as $cart_item ) {
            
$normalized_qty $quantity_limits->normalize_cart_item_quantity$cart_item['quantity'], $cart_item );

            if ( 
$normalized_qty !== $cart_item['quantity'] ) {
                
$this->set_cart_item_quantity$cart_item['key'], $normalized_qty );
            }
        }
    }

    
/**
     * Gets the latest cart instance, and ensures totals have been calculated before returning.
     *
     * @return \WC_Cart
     */
    
public function get_cart_for_response() {
        return 
did_action'woocommerce_after_calculate_totals' ) ? $this->get_cart_instance() : $this->calculate_totals();
    }

    
/**
     * Recalculates the cart totals and returns the updated cart instance.
     *
     * @since 9.2.0 Calculate shipping was removed here because it's called already by calculate_totals.
     *
     * @return \WC_Cart
     */
    
public function calculate_totals() {
        
$cart $this->get_cart_instance();
        
$cart->get_cart();
        
$cart->calculate_fees();
        
$cart->calculate_totals();
        return 
$cart;
    }

    
/**
     * Based on the core cart class but returns errors rather than rendering notices directly.
     *
     * @todo Overriding the core add_to_cart method was necessary because core outputs notices when an item is added to
     * the cart. For us this would cause notices to build up and output on the store, out of context. Core would need
     * refactoring to split notices out from other cart actions.
     *
     * @throws RouteException Exception if invalid data is detected.
     *
     * @param array $request Add to cart request params.
     * @return string
     */
    
public function add_to_cart$request ) {
        
$cart    $this->get_cart_instance();
        
$request wp_parse_args(
            
$request,
            [
                
'id'             => 0,
                
'quantity'       => 1,
                
'variation'      => [],
                
'cart_item_data' => [],
            ]
        );

        
$request $this->filter_request_data$this->parse_variation_data$request ) );
        
$product $this->get_product_for_cart$request );
        
$cart_id $cart->generate_cart_id(
            
$this->get_product_id$product ),
            
$this->get_variation_id$product ),
            
$request['variation'],
            
$request['cart_item_data']
        );

        
$this->validate_add_to_cart$product$request );

        
$quantity_limits  = new QuantityLimits();
        
$existing_cart_id $cart->find_product_in_cart$cart_id );

        if ( 
$existing_cart_id ) {
            
$cart_item           $cart->cart_contents$existing_cart_id ];
            
$quantity_validation $quantity_limits->validate_cart_item_quantity$request['quantity'] + $cart_item['quantity'], $cart_item );

            if ( 
is_wp_error$quantity_validation ) ) {
                throw new 
RouteException$quantity_validation->get_error_code(), $quantity_validation->get_error_message(), 400 );
            }

            
$cart->set_quantity$existing_cart_id$request['quantity'] + $cart->cart_contents$existing_cart_id ]['quantity'], true );

            return 
$existing_cart_id;
        }

        
// Normalize quantity.
        
$add_to_cart_limits $quantity_limits->get_add_to_cart_limits$product );
        
$request_quantity   = (int) $request['quantity'];

        if ( 
$add_to_cart_limits['maximum'] ) {
            
$request_quantity min$request_quantity$add_to_cart_limits['maximum'] );
        }

        
$request_quantity max$request_quantity$add_to_cart_limits['minimum'] );
        
$request_quantity $quantity_limits->limit_to_multiple$request_quantity$add_to_cart_limits['multiple_of'] );

        
/**
         * Filters the item being added to the cart.
         *
         * @since 2.5.0
         *
         * @internal Matches filter name in WooCommerce core.
         *
         * @param array $cart_item_data Array of cart item data being added to the cart.
         * @param string $cart_id Id of the item in the cart.
         * @return array Updated cart item data.
         */
        
$cart->cart_contents$cart_id ] = apply_filters(
            
'woocommerce_add_cart_item',
            
array_merge(
                
$request['cart_item_data'],
                array(
                    
'key'          => $cart_id,
                    
'product_id'   => $this->get_product_id$product ),
                    
'variation_id' => $this->get_variation_id$product ),
                    
'variation'    => $request['variation'],
                    
'quantity'     => $request_quantity,
                    
'data'         => $product,
                    
'data_hash'    => wc_get_cart_item_data_hash$product ),
                )
            ),
            
$cart_id
        
);

        
/**
         * Filters the entire cart contents when the cart changes.
         *
         * @since 2.5.0
         *
         * @internal Matches filter name in WooCommerce core.
         *
         * @param array $cart_contents Array of all cart items.
         * @return array Updated array of all cart items.
         */
        
$cart->cart_contents apply_filters'woocommerce_cart_contents_changed'$cart->cart_contents );

        
/**
         * Fires when an item is added to the cart.
         *
         * This hook fires when an item is added to the cart. This is triggered from the Store API in this context, but
         * WooCommerce core add to cart events trigger the same hook.
         *
         * @since 2.5.0
         *
         * @internal Matches action name in WooCommerce core.
         *
         * @param string $cart_id ID of the item in the cart.
         * @param integer $product_id ID of the product added to the cart.
         * @param integer $request_quantity Quantity of the item added to the cart.
         * @param integer $variation_id Variation ID of the product added to the cart.
         * @param array $variation Array of variation data.
         * @param array $cart_item_data Array of other cart item data.
         */
        
do_action(
            
'woocommerce_add_to_cart',
            
$cart_id,
            
$this->get_product_id$product ),
            
$request_quantity,
            
$this->get_variation_id$product ),
            
$request['variation'],
            
$request['cart_item_data']
        );

        return 
$cart_id;
    }

    
/**
     * Based on core `set_quantity` method, but validates if an item is sold individually first and enforces any limits in
     * place.
     *
     * @throws RouteException Exception if invalid data is detected.
     *
     * @param string  $item_id Cart item id.
     * @param integer $quantity Cart quantity.
     */
    
public function set_cart_item_quantity$item_id$quantity ) {
        
$cart_item $this->get_cart_item$item_id );

        if ( empty( 
$cart_item ) ) {
            throw new 
RouteException'woocommerce_rest_cart_invalid_key'esc_html__'Cart item does not exist.''woocommerce' ), 409 );
        }

        
$product $cart_item['data'] ?? false;

        if ( ! 
$product instanceof \WC_Product ) {
            throw new 
RouteException'woocommerce_rest_cart_invalid_product'esc_html__'Cart item is invalid.''woocommerce' ), 404 );
        }

        
$quantity_validation = ( new QuantityLimits() )->validate_cart_item_quantity$quantity$cart_item );

        if ( 
is_wp_error$quantity_validation ) ) {
            throw new 
RouteException$quantity_validation->get_error_code(), $quantity_validation->get_error_message(), 400 ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
        
}

        
$cart $this->get_cart_instance();
        
$cart->set_quantity$item_id$quantity );
    }

    
/**
     * Validate all items in the cart and check for errors.
     *
     * @throws RouteException Exception if invalid data is detected.
     *
     * @param \WC_Product $product Product object associated with the cart item.
     * @param array       $request Add to cart request params.
     */
    
public function validate_add_to_cart\WC_Product $product$request ) {
        if ( ! 
$product->is_purchasable() ) {
            
$this->throw_default_product_exception$product );
        }

        if ( ! 
$product->is_in_stock() ) {
            throw new 
RouteException(
                
'woocommerce_rest_product_out_of_stock',
                
sprintf(
                    
/* translators: %s: product name */
                    
__'You cannot add &quot;%s&quot; to the cart because the product is out of stock.''woocommerce' ),
                    
$product->get_name()
                ),
                
400
            
);
        }

        if ( 
$product->managing_stock() && ! $product->backorders_allowed() ) {
            
$qty_remaining $this->get_remaining_stock_for_product$product );
            
$qty_in_cart   $this->get_product_quantity_in_cart$product );

            if ( 
$qty_remaining $qty_in_cart $request['quantity'] ) {
                throw new 
RouteException(
                    
'woocommerce_rest_product_partially_out_of_stock',
                    
sprintf(
                        
/* translators: 1: product name 2: quantity in stock */
                        
__'You cannot add that amount of &quot;%1$s&quot; to the cart because there is not enough stock (%2$s remaining).''woocommerce' ),
                        
$product->get_name(),
                        
wc_format_stock_quantity_for_display$qty_remaining$product )
                    ),
                    
400
                
);
            }
        }

        
/**
         * Filters if an item being added to the cart passed validation checks.
         *
         * Allow 3rd parties to validate if an item can be added to the cart. This is a legacy hook from Woo core.
         * This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture
         * notices and convert to exceptions instead.
         *
         * @since 7.2.0
         *
         * @deprecated
         * @param boolean $passed_validation True if the item passed validation.
         * @param integer $product_id Product ID being validated.
         * @param integer $quantity Quantity added to the cart.
         * @param integer $variation_id Variation ID being added to the cart.
         * @param array $variation Variation data.
         * @return boolean
         */
        
$passed_validation apply_filters(
            
'woocommerce_add_to_cart_validation',
            
true,
            
$this->get_product_id$product ),
            
$request['quantity'],
            
$this->get_variation_id$product ),
            
$request['variation'],
            
$request['cart_item_data']
        );

        if ( ! 
$passed_validation ) {
            
// Validation did not pass - see if an error notice was thrown.
            
NoticeHandler::convert_notices_to_exceptions'woocommerce_rest_add_to_cart_error' );

            
// If no notice was thrown, throw the default notice instead.
            
$this->throw_default_product_exception$product );
        }

        
/**
         * Fires during validation when adding an item to the cart via the Store API.
         *
         * @param \WC_Product $product Product object being added to the cart.
         * @param array       $request Add to cart request params including id, quantity, and variation attributes.
         * @deprecated 7.1.0 Use woocommerce_store_api_validate_add_to_cart instead.
         */
        
wc_do_deprecated_action(
            
'wooocommerce_store_api_validate_add_to_cart',
            array(
                
$product,
                
$request,
            ),
            
'7.1.0',
            
'woocommerce_store_api_validate_add_to_cart',
            
'This action was deprecated in WooCommerce Blocks version 7.1.0. Please use woocommerce_store_api_validate_add_to_cart instead.'
        
);

        
/**
         * Fires during validation when adding an item to the cart via the Store API.
         *
         * Fire action to validate add to cart. Functions hooking into this should throw an \Exception to prevent
         * add to cart from happening.
         *
         * @since 7.1.0
         *
         * @param \WC_Product $product Product object being added to the cart.
         * @param array       $request Add to cart request params including id, quantity, and variation attributes.
         */
        
do_action'woocommerce_store_api_validate_add_to_cart'$product$request );
    }

    
/**
     * Generates the error message for out of stock products and adds product names to it.
     *
     * @param string $singular The message to use when only one product is in the list.
     * @param string $plural The message to use when more than one product is in the list.
     * @param array  $items The list of cart items whose names should be inserted into the message.
     * @returns string The translated and correctly pluralised message.
     */
    
private function add_product_names_to_message$singular$plural$items ) {
        
$product_names wc_list_pluck$items'getProductName' );
        
$message       = ( count$items ) > ) ? $plural $singular;
        return 
sprintf(
            
$message,
            
ArrayUtils::natural_language_join$product_namestrue )
        );
    }

    
/**
     * Takes a string describing the type of stock extension, whether there is a single product or multiple products
     * causing this exception and returns an appropriate error message.
     *
     * @param string $exception_type     The type of exception encountered.
     * @param string $singular_or_plural Whether to get the error message for a single product or multiple.
     *
     * @return string
     */
    
private function get_error_message_for_stock_exception_type$exception_type$singular_or_plural ) {
        
$stock_error_messages = [
            
'out_of_stock'         => [
                
/* translators: %s: product name. */
                
'singular' => __(
                    
'%s is out of stock and cannot be purchased. Please remove it from your cart.',
                    
'woocommerce'
                
),
                
/* translators: %s: product names. */
                
'plural'   => __(
                    
'%s are out of stock and cannot be purchased. Please remove them from your cart.',
                    
'woocommerce'
                
),
            ],
            
'not_purchasable'      => [
                
/* translators: %s: product name. */
                
'singular' => __(
                    
'%s cannot be purchased. Please remove it from your cart.',
                    
'woocommerce'
                
),
                
/* translators: %s: product names. */
                
'plural'   => __(
                    
'%s cannot be purchased. Please remove them from your cart.',
                    
'woocommerce'
                
),
            ],
            
'too_many_in_cart'     => [
                
/* translators: %s: product names. */
                
'singular' => __(
                    
'There are too many %s in the cart. Only 1 can be purchased. Please reduce the quantity in your cart.',
                    
'woocommerce'
                
),
                
/* translators: %s: product names. */
                
'plural'   => __(
                    
'There are too many %s in the cart. Only 1 of each can be purchased. Please reduce the quantities in your cart.',
                    
'woocommerce'
                
),
            ],
            
'partial_out_of_stock' => [
                
/* translators: %s: product names. */
                
'singular' => __(
                    
'There is not enough %s in stock. Please reduce the quantity in your cart.',
                    
'woocommerce'
                
),
                
/* translators: %s: product names. */
                
'plural'   => __(
                    
'There are not enough %s in stock. Please reduce the quantities in your cart.',
                    
'woocommerce'
                
),
            ],
        ];

        if (
            isset( 
$stock_error_messages$exception_type ] ) &&
            isset( 
$stock_error_messages$exception_type ][ $singular_or_plural ] )
        ) {
            return 
$stock_error_messages$exception_type ][ $singular_or_plural ];
        }

        return 
__'There was an error with an item in your cart.''woocommerce' );
    }

    
/**
     * Validate cart and check for errors.
     *
     * @throws InvalidCartException Exception if invalid data is detected in the cart.
     */
    
public function validate_cart() {
        
$this->validate_cart_items();
        
$this->validate_cart_coupons();

        
$cart        $this->get_cart_instance();
        
$cart_errors = new WP_Error();

        
/**
         * Fires an action to validate the cart.
         *
         * Functions hooking into this should add custom errors using the provided WP_Error instance.
         *
         * @since 7.2.0
         *
         * @example See docs/examples/validate-cart.md
         *
         * @param \WP_Error $errors  WP_Error object.
         * @param \WC_Cart  $cart    Cart object.
         */
        
do_action'woocommerce_store_api_cart_errors'$cart_errors$cart );

        if ( 
$cart_errors->has_errors() ) {
            throw new 
InvalidCartException(
                
'woocommerce_cart_error',
                
$cart_errors,
                
409
            
);
        }

        
// Before running the woocommerce_check_cart_items hook, unhook validation from the core cart.
        
remove_action'woocommerce_check_cart_items', array( $cart'check_cart_items' ), );
        
remove_action'woocommerce_check_cart_items', array( $cart'check_cart_coupons' ), );

        
/**
         * Fires when cart items are being validated.
         *
         * Allow 3rd parties to validate cart items. This is a legacy hook from Woo core.
         * This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture
         * notices and convert to wp errors instead.
         *
         * @since 7.2.0
         *
         * @deprecated
         * @internal Matches action name in WooCommerce core.
         */
        
do_action'woocommerce_check_cart_items' );

        
$cart_errors NoticeHandler::convert_notices_to_wp_errors'woocommerce_rest_cart_item_error' );

        if ( 
$cart_errors->has_errors() ) {
            throw new 
InvalidCartException(
                
'woocommerce_cart_error',
                
$cart_errors,
                
409
            
);
        }
    }

    
/**
     * When placing an order, validate that the cart is not empty.
     *
     * @throws InvalidCartException Exception if the cart is empty.
     */
    
public function validate_cart_not_empty() {
        
$cart_items $this->get_cart_items();

        if ( empty( 
$cart_items ) ) {
            throw new 
InvalidCartException(
                
'woocommerce_cart_error',
                
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Errors are converted to response objects later.
                
new WP_Error'woocommerce_rest_cart_empty'__'Cannot place an order, your cart is empty.''woocommerce' ), 400 ),
                
400
            
);
        }
    }

    
/**
     * Validate all items in the cart and check for errors.
     *
     * @throws InvalidCartException Exception if invalid data is detected due to insufficient stock levels.
     */
    
public function validate_cart_items() {
        
$cart_items $this->get_cart_items();

        
$errors                        = [];
        
$out_of_stock_products         = [];
        
$too_many_in_cart_products     = [];
        
$partial_out_of_stock_products = [];
        
$not_purchasable_products      = [];

        foreach ( 
$cart_items as $cart_item ) {
            try {
                
$this->validate_cart_item$cart_item );
            } catch ( 
RouteException $error ) {
                
$errors[] = new WP_Error$error->getErrorCode(), $error->getMessage(), $error->getAdditionalData() );
            } catch ( 
TooManyInCartException $error ) {
                
$too_many_in_cart_products[] = $error;
            } catch ( 
NotPurchasableException $error ) {
                
$not_purchasable_products[] = $error;
            } catch ( 
PartialOutOfStockException $error ) {
                
$partial_out_of_stock_products[] = $error;
            } catch ( 
OutOfStockException $error ) {
                
$out_of_stock_products[] = $error;
            }
        }

        if ( 
count$errors ) > ) {

            
$error = new WP_Error();
            foreach ( 
$errors as $wp_error ) {
                
$error->merge_from$wp_error );
            }

            throw new 
InvalidCartException(
                
'woocommerce_cart_error',
                
$error,
                
409
            
);
        }

        
$error $this->stock_exceptions_to_wp_errors$too_many_in_cart_products$not_purchasable_products$partial_out_of_stock_products$out_of_stock_products );
        if ( 
$error->has_errors() ) {

            throw new 
InvalidCartException(
                
'woocommerce_stock_availability_error',
                
$error,
                
409
            
);
        }
    }

    
/**
     * This method will take arrays of exceptions relating to stock, and will convert them to a WP_Error object.
     *
     * @param TooManyInCartException[]     $too_many_in_cart_products     Array of TooManyInCartExceptions.
     * @param NotPurchasableException[]    $not_purchasable_products      Array of NotPurchasableExceptions.
     * @param PartialOutOfStockException[] $partial_out_of_stock_products Array of PartialOutOfStockExceptions.
     * @param OutOfStockException[]        $out_of_stock_products         Array of OutOfStockExceptions.
     *
     * @return WP_Error  The WP_Error object returned. Will have errors if any exceptions were in the args. It will be empty if they do not.
     */
    
private function stock_exceptions_to_wp_errors$too_many_in_cart_products$not_purchasable_products$partial_out_of_stock_products$out_of_stock_products ) {
        
$error = new WP_Error();

        if ( 
count$out_of_stock_products ) > ) {

            
$singular_error $this->get_error_message_for_stock_exception_type'out_of_stock''singular' );
            
$plural_error   $this->get_error_message_for_stock_exception_type'out_of_stock''plural' );

            
$error->add(
                
'woocommerce_rest_product_out_of_stock',
                
$this->add_product_names_to_message$singular_error$plural_error$out_of_stock_products )
            );
        }

        if ( 
count$not_purchasable_products ) > ) {
            
$singular_error $this->get_error_message_for_stock_exception_type'not_purchasable''singular' );
            
$plural_error   $this->get_error_message_for_stock_exception_type'not_purchasable''plural' );

            
$error->add(
                
'woocommerce_rest_product_not_purchasable',
                
$this->add_product_names_to_message$singular_error$plural_error$not_purchasable_products )
            );
        }

        if ( 
count$too_many_in_cart_products ) > ) {
            
$singular_error $this->get_error_message_for_stock_exception_type'too_many_in_cart''singular' );
            
$plural_error   $this->get_error_message_for_stock_exception_type'too_many_in_cart''plural' );

            
$error->add(
                
'woocommerce_rest_product_too_many_in_cart',
                
$this->add_product_names_to_message$singular_error$plural_error$too_many_in_cart_products )
            );
        }

        if ( 
count$partial_out_of_stock_products ) > ) {
            
$singular_error $this->get_error_message_for_stock_exception_type'partial_out_of_stock''singular' );
            
$plural_error   $this->get_error_message_for_stock_exception_type'partial_out_of_stock''plural' );

            
$error->add(
                
'woocommerce_rest_product_partially_out_of_stock',
                
$this->add_product_names_to_message$singular_error$plural_error$partial_out_of_stock_products )
            );
        }

        return 
$error;
    }

    
/**
     * Validates an existing cart item and returns any errors.
     *
     * @throws TooManyInCartException Exception if more than one product that can only be purchased individually is in
     * the cart.
     * @throws PartialOutOfStockException Exception if an item has a quantity greater than what is available in stock.
     * @throws OutOfStockException Exception thrown when an item is entirely out of stock.
     * @throws NotPurchasableException Exception thrown when an item is not purchasable.
     * @param array $cart_item Cart item array.
     */
    
public function validate_cart_item$cart_item ) {
        
$product $cart_item['data'] ?? false;

        if ( ! 
$product instanceof \WC_Product ) {
            return;
        }

        if ( ! 
$product->is_purchasable() ) {
            throw new 
NotPurchasableException(
                
'woocommerce_rest_product_not_purchasable',
                
$product->get_name()
            );
        }

        if ( 
$product->is_sold_individually() && $cart_item['quantity'] > ) {
            throw new 
TooManyInCartException(
                
'woocommerce_rest_product_too_many_in_cart',
                
$product->get_name()
            );
        }

        if ( ! 
$product->is_in_stock() ) {
            throw new 
OutOfStockException(
                
'woocommerce_rest_product_out_of_stock',
                
$product->get_name()
            );
        }

        if ( 
$product->managing_stock() && ! $product->backorders_allowed() ) {
            
$qty_remaining $this->get_remaining_stock_for_product$product );
            
$qty_in_cart   $this->get_product_quantity_in_cart$product );

            if ( 
$qty_remaining $qty_in_cart ) {
                throw new 
PartialOutOfStockException(
                    
'woocommerce_rest_product_partially_out_of_stock',
                    
$product->get_name()
                );
            }
        }

        
/**
         * Fire action to validate add to cart. Functions hooking into this should throw an \Exception to prevent
         * add to cart from occurring.
         *
         * @param \WC_Product $product Product object being added to the cart.
         * @param array       $cart_item Cart item array.
         * @deprecated 7.1.0 Use woocommerce_store_api_validate_cart_item instead.
         */
        
wc_do_deprecated_action(
            
'wooocommerce_store_api_validate_cart_item',
            array(
                
$product,
                
$cart_item,
            ),
            
'7.1.0',
            
'woocommerce_store_api_validate_cart_item',
            
'This action was deprecated in WooCommerce Blocks version 7.1.0. Please use woocommerce_store_api_validate_cart_item instead.'
        
);

        
/**
         * Fire action to validate add to cart. Functions hooking into this should throw an \Exception to prevent
         * add to cart from occurring.
         *
         * @since 7.1.0
         *
         * @param \WC_Product $product Product object being added to the cart.
         * @param array       $cart_item Cart item array.
         */
        
do_action'woocommerce_store_api_validate_cart_item'$product$cart_item );
    }

    
/**
     * Validate all coupons in the cart and check for errors.
     *
     * @throws InvalidCartException Exception if invalid data is detected.
     */
    
public function validate_cart_coupons() {
        
$cart_coupons $this->get_cart_coupons();
        
$errors       = [];

        foreach ( 
$cart_coupons as $code ) {
            
$coupon = new \WC_Coupon$code );
            try {
                
$this->validate_cart_coupon$coupon );
            } catch ( 
RouteException $error ) {
                
$errors[] = new WP_Error$error->getErrorCode(), $error->getMessage(), $error->getAdditionalData() );
            }
        }

        if ( ! empty( 
$errors ) ) {

            
$error = new WP_Error();
            foreach ( 
$errors as $wp_error ) {
                
$error->merge_from$wp_error );
            }

            throw new 
InvalidCartException(
                
'woocommerce_coupons_error',
                
$error,
                
409
            
);
        }
    }

    
/**
     * Validate the cart and get a list of errors.
     *
     * @return WP_Error A WP_Error instance containing the cart's errors.
     */
    
public function get_cart_errors() {
        
$errors = new WP_Error();

        try {
            
$this->validate_cart();
        } catch ( 
RouteException $error ) {
            
$errors->add$error->getErrorCode(), $error->getMessage(), $error->getAdditionalData() );
        } catch ( 
InvalidCartException $error ) {
            
$errors->merge_from$error->getError() );
        } catch ( 
\Exception $error ) {
            
$errors->add$error->getCode(), $error->getMessage() );
        }

        return 
$errors;
    }

    
/**
     * Get main instance of cart class.
     *
     * @throws RouteException When cart cannot be loaded.
     * @return \WC_Cart
     */
    
public function get_cart_instance() {
        
$cart wc()->cart;

        if ( ! 
$cart || ! $cart instanceof \WC_Cart ) {
            throw new 
RouteException'woocommerce_rest_cart_error'esc_html__'Unable to retrieve cart.''woocommerce' ), 500 );
        }

        return 
$cart;
    }

    
/**
     * Return a cart item from the woo core cart class.
     *
     * @param string $item_id Cart item id.
     * @return array
     */
    
public function get_cart_item$item_id ) {
        
$cart $this->get_cart_instance();
        return isset( 
$cart->cart_contents$item_id ] ) ? $cart->cart_contents$item_id ] : [];
    }

    
/**
     * Returns all cart items.
     *
     * @param callable $callback Optional callback to apply to the array filter.
     * @return array
     */
    
public function get_cart_items$callback null ) {
        
$cart $this->get_cart_instance();
        return 
$callback array_filter$cart->get_cart(), $callback ) : array_filter$cart->get_cart() );
    }

    
/**
     * Get hashes for items in the current cart. Useful for tracking changes.
     *
     * @return array
     */
    
public function get_cart_hashes() {
        
$cart $this->get_cart_instance();
        return [
            
'line_items' => $cart->get_cart_hash(),
            
'shipping'   => md5wp_json_encode$cart->shipping_methods ) ),
            
'fees'       => md5wp_json_encode$cart->get_fees() ) ),
            
'coupons'    => md5wp_json_encode$cart->get_applied_coupons() ) ),
            
'taxes'      => md5wp_json_encode$cart->get_taxes() ) ),
        ];
    }

    
/**
     * Empty cart contents.
     */
    
public function empty_cart() {
        
$cart $this->get_cart_instance();
        
$cart->empty_cart();
    }

    
/**
     * See if cart has applied coupon by code.
     *
     * @param string $coupon_code Cart coupon code.
     * @return bool
     */
    
public function has_coupon$coupon_code ) {
        
$cart $this->get_cart_instance();
        return 
$cart->has_discount$coupon_code );
    }

    
/**
     * Returns all applied coupons.
     *
     * @param callable $callback Optional callback to apply to the array filter.
     * @return array
     */
    
public function get_cart_coupons$callback null ) {
        
$cart $this->get_cart_instance();
        return 
$callback array_filter$cart->get_applied_coupons(), $callback ) : array_filter$cart->get_applied_coupons() );
    }

    
/**
     * Get shipping packages from the cart with calculated shipping rates.
     *
     * @todo this can be refactored once https://github.com/woocommerce/woocommerce/pull/26101 lands.
     *
     * @param bool $calculate_rates Should rates for the packages also be returned.
     * @return array
     */
    
public function get_shipping_packages$calculate_rates true ) {
        
$cart $this->get_cart_instance();

        
// See if we need to calculate anything.
        
if ( ! $cart->needs_shipping() ) {
            return [];
        }

        
$packages $cart->get_shipping_packages();

        
// Return early if invalid object supplied by the filter or no packages.
        
if ( ! is_array$packages ) || empty( $packages ) ) {
            return [];
        }

        
// Add extra package data to array.
        
$packages array_map(
            function ( 
$key$package$index ) {
                
$package['package_id']   = isset( $package['package_id'] ) ? $package['package_id'] : $key;
                
$package['package_name'] = isset( $package['package_name'] ) ? $package['package_name'] : $this->get_package_name$package$index );
                return 
$package;
            },
            
array_keys$packages ),
            
$packages,
            
range1count$packages ) )
        );

        return 
$calculate_rates wc()->shipping()->calculate_shipping$packages ) : $packages;
    }

    
/**
     * Creates a name for a package.
     *
     * @param array $package Shipping package from WooCommerce.
     * @param int   $index Package number.
     * @return string
     */
    
protected function get_package_name$package$index ) {
        
/**
         * Filters the shipping package name.
         *
         * @since 4.3.0
         *
         * @internal Matches filter name in WooCommerce core.
         *
         * @param string $shipping_package_name Shipping package name.
         * @param string $package_id Shipping package ID.
         * @param array $package Shipping package from WooCommerce.
         * @return string Shipping package name.
         */
        
return apply_filters(
            
'woocommerce_shipping_package_name',
            
$index ?
                
sprintf(
                    
/* translators: %d: shipping package number */
                    
_x'Shipment %d''shipping packages''woocommerce' ),
                    
$index
                
) :
                
_x'Shipment 1''shipping packages''woocommerce' ),
            
$package['package_id'],
            
$package
        
);
    }

    
/**
     * Selects a shipping rate.
     *
     * @param int|string $package_id ID of the package to choose a rate for.
     * @param string     $rate_id ID of the rate being chosen.
     */
    
public function select_shipping_rate$package_id$rate_id ) {
        if ( ! 
is_string$rate_id ) ) {
            return;
        }
        
$cart                        $this->get_cart_instance();
        
$session_data                wc()->session->get'chosen_shipping_methods' ) ? wc()->session->get'chosen_shipping_methods' ) : [];
        
$session_data$package_id ] = $rate_id;

        
wc()->session->set'chosen_shipping_methods'$session_data );
    }

    
/**
     * Based on the core cart class but returns errors rather than rendering notices directly.
     *
     * @todo Overriding the core apply_coupon method was necessary because core outputs notices when a coupon gets
     * applied. For us this would cause notices to build up and output on the store, out of context. Core would need
     * refactoring to split notices out from other cart actions.
     *
     * @throws RouteException Exception if invalid data is detected.
     *
     * @param string $coupon_code Coupon code.
     */
    
public function apply_coupon$coupon_code ) {
        
$cart            $this->get_cart_instance();
        
$applied_coupons $this->get_cart_coupons();
        
$coupon          = new \WC_Coupon$coupon_code );

        if ( 
$coupon->get_code() !== $coupon_code ) {
            throw new 
RouteException(
                
'woocommerce_rest_cart_coupon_error',
                
sprintf(
                    
/* translators: %s coupon code */
                    
esc_html__'"%s" is an invalid coupon code.''woocommerce' ),
                    
esc_html$coupon_code )
                ),
                
400
            
);
        }

        if ( 
$this->has_coupon$coupon_code ) ) {
            throw new 
RouteException(
                
'woocommerce_rest_cart_coupon_error',
                
sprintf(
                    
/* translators: %s coupon code */
                    
esc_html__'Coupon code "%s" has already been applied.''woocommerce' ),
                    
esc_html$coupon_code )
                ),
                
400
            
);
        }

        
$discounts = new \WC_Discounts$this->get_cart_instance() );
        
$valid     $discounts->is_coupon_valid$coupon );

        if ( 
is_wp_error$valid ) ) {
            throw new 
RouteException(
                
'woocommerce_rest_cart_coupon_error',
                
esc_htmlwp_strip_all_tags$valid->get_error_message() ) ),
                
400,
                
$valid->get_error_data() // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            
);
        }

        
// Prevents new coupons being added if individual use coupons are already in the cart.
        
$individual_use_coupons $this->get_cart_coupons(
            function ( 
$code ) {
                
$coupon = new \WC_Coupon$code );
                return 
$coupon->get_individual_use();
            }
        );

        foreach ( 
$individual_use_coupons as $code ) {
            
$individual_use_coupon = new \WC_Coupon$code );

            
/**
             * Filters if a coupon can be applied alongside other individual use coupons.
             *
             * @since 2.6.0
             *
             * @internal Matches filter name in WooCommerce core.
             *
             * @param boolean $apply_with_individual_use_coupon Defaults to false.
             * @param \WC_Coupon $coupon Coupon object applied to the cart.
             * @param \WC_Coupon $individual_use_coupon Individual use coupon already applied to the cart.
             * @param array $applied_coupons Array of applied coupons already applied to the cart.
             * @return boolean
             */
            
if ( false === apply_filters'woocommerce_apply_with_individual_use_coupon'false$coupon$individual_use_coupon$applied_coupons ) ) {
                throw new 
RouteException(
                    
'woocommerce_rest_cart_coupon_error',
                    
sprintf(
                        
/* translators: %s: coupon code */
                        
esc_html__'"%s" has already been applied and cannot be used in conjunction with other coupons.''woocommerce' ),
                        
esc_html$code )
                    ),
                    
400
                
);
            }
        }

        if ( 
$coupon->get_individual_use() ) {
            
/**
             * Filter coupons to remove when applying an individual use coupon.
             *
             * @since 2.6.0
             *
             * @internal Matches filter name in WooCommerce core.
             *
             * @param array $coupons Array of coupons to remove from the cart.
             * @param \WC_Coupon $coupon Coupon object applied to the cart.
             * @param array $applied_coupons Array of applied coupons already applied to the cart.
             * @return array
             */
            
$coupons_to_remove array_diff$applied_couponsapply_filters'woocommerce_apply_individual_use_coupon', array(), $coupon$applied_coupons ) );

            foreach ( 
$coupons_to_remove as $code ) {
                
$cart->remove_coupon$code );
            }

            
$applied_coupons array_diff$applied_coupons$coupons_to_remove );
        }

        
$applied_coupons[] = $coupon_code;
        
$cart->set_applied_coupons$applied_coupons );

        
/**
         * Fires after a coupon has been applied to the cart.
         *
         * @since 2.6.0
         *
         * @internal Matches action name in WooCommerce core.
         *
         * @param string $coupon_code The coupon code that was applied.
         */
        
do_action'woocommerce_applied_coupon'$coupon_code );
    }

    
/**
     * Validates an existing cart coupon and returns any errors.
     *
     * @param \WC_Coupon $coupon Coupon object applied to the cart.
     *
     * @throws RouteException Exception if invalid data is detected.
     */
    
protected function validate_cart_coupon\WC_Coupon $coupon ) {
        if ( ! 
$coupon->is_valid() ) {
            
$cart $this->get_cart_instance();
            
$cart->remove_coupon$coupon->get_code() );
            
$cart->calculate_totals();
            throw new 
RouteException(
                
'woocommerce_rest_cart_coupon_error',
                
sprintf(
                    
/* translators: %1$s coupon code, %2$s reason. */
                    
__'The "%1$s" coupon has been removed from your cart: %2$s''woocommerce' ),
                    
$coupon->get_code(),
                    
wp_strip_all_tags$coupon->get_error_message() )
                ),
                
409
            
);
        }
    }

    
/**
     * Gets the qty of a product across line items.
     *
     * @param \WC_Product $product Product object.
     * @return int
     */
    
protected function get_product_quantity_in_cart$product ) {
        
$cart               $this->get_cart_instance();
        
$product_quantities $cart->get_cart_item_quantities();
        
$product_id         $product->get_stock_managed_by_id();

        return isset( 
$product_quantities$product_id ] ) ? $product_quantities$product_id ] : 0;
    }

    
/**
     * Gets remaining stock for a product.
     *
     * @param \WC_Product $product Product object.
     * @return int
     */
    
protected function get_remaining_stock_for_product$product ) {
        
$reserve_stock = new ReserveStock();
        
$qty_reserved  $reserve_stock->get_reserved_stock$product$this->get_draft_order_id() );

        return 
$product->get_stock_quantity() - $qty_reserved;
    }

    
/**
     * Get a product object to be added to the cart.
     *
     * @throws RouteException Exception if invalid data is detected.
     *
     * @param array $request Add to cart request params.
     * @return \WC_Product|Error Returns a product object if purchasable.
     */
    
protected function get_product_for_cart$request ) {
        
$product wc_get_product$request['id'] );

        if ( ! 
$product || ProductStatus::TRASH === $product->get_status() ) {
            throw new 
RouteException(
                
'woocommerce_rest_cart_invalid_product',
                
__'This product cannot be added to the cart.''woocommerce' ),
                
400
            
);
        }

        return 
$product;
    }

    
/**
     * For a given product, get the product ID.
     *
     * @param \WC_Product $product Product object associated with the cart item.
     * @return int
     */
    
protected function get_product_id\WC_Product $product ) {
        return 
$product->is_typeProductType::VARIATION ) ? $product->get_parent_id() : $product->get_id();
    }

    
/**
     * For a given product, get the variation ID.
     *
     * @param \WC_Product $product Product object associated with the cart item.
     * @return int
     */
    
protected function get_variation_id\WC_Product $product ) {
        return 
$product->is_typeProductType::VARIATION ) ? $product->get_id() : 0;
    }

    
/**
     * Default exception thrown when an item cannot be added to the cart.
     *
     * @throws RouteException Exception with code woocommerce_rest_product_not_purchasable.
     *
     * @param \WC_Product $product Product object associated with the cart item.
     */
    
protected function throw_default_product_exception\WC_Product $product ) {
        throw new 
RouteException(
            
'woocommerce_rest_product_not_purchasable',
            
sprintf(
                
/* translators: %s: product name */
                
__'&quot;%s&quot; is not available for purchase.''woocommerce' ),
                
$product->get_name()
            ),
            
400
        
);
    }

    
/**
     * Filter data for add to cart requests.
     *
     * @param array $request Add to cart request params.
     * @return array Updated request array.
     */
    
protected function filter_request_data$request ) {
        
$product_id   $request['id'];
        
$variation_id 0;
        
$product      wc_get_product$product_id );

        if ( 
$product->is_typeProductType::VARIATION ) ) {
            
$product_id   $product->get_parent_id();
            
$variation_id $product->get_id();
        }

        
/**
         * Filter cart item data for add to cart requests.
         *
         * @since 2.5.0
         *
         * @internal Matches filter name in WooCommerce core.
         *
         * @param array $cart_item_data Array of other cart item data.
         * @param integer $product_id ID of the product added to the cart.
         * @param integer $variation_id Variation ID of the product added to the cart.
         * @param integer $quantity Quantity of the item added to the cart.
         * @return array
         */
        
$request['cart_item_data'] = (array) apply_filters(
            
'woocommerce_add_cart_item_data',
            
$request['cart_item_data'],
            
$product_id,
            
$variation_id,
            
$request['quantity']
        );

        if ( 
$product->is_sold_individually() ) {
            
/**
             * Filter sold individually quantity for add to cart requests.
             *
             * @since 2.5.0
             *
             * @internal Matches filter name in WooCommerce core.
             *
             * @param integer $sold_individually_quantity Defaults to 1.
             * @param integer $quantity Quantity of the item added to the cart.
             * @param integer $product_id ID of the product added to the cart.
             * @param integer $variation_id Variation ID of the product added to the cart.
             * @param array $cart_item_data Array of other cart item data.
             * @return integer
             */
            
$request['quantity'] = apply_filters'woocommerce_add_to_cart_sold_individually_quantity'1$request['quantity'], $product_id$variation_id$request['cart_item_data'] );
        }

        return 
$request;
    }

    
/**
     * If variations are set, validate and format the values ready to add to the cart.
     *
     * @throws RouteException Exception if invalid data is detected.
     *
     * @param array $request Add to cart request params.
     * @return array Updated request array.
     */
    
protected function parse_variation_data$request ) {
        
$product $this->get_product_for_cart$request );

        
// Remove variation request if not needed.
        
if ( ! $product->is_type( array( ProductType::VARIATIONProductType::VARIABLE ) ) ) {
            
$request['variation'] = [];
            return 
$request;
        }

        
// Flatten data and format posted values.
        
$variable_product_attributes $this->get_variable_product_attributes$product );
        
$request['variation']        = $this->sanitize_variation_datawp_list_pluck$request['variation'], 'value''attribute' ), $variable_product_attributes );

        
// If we have a parent product, find the variation ID.
        
if ( $product->is_typeProductType::VARIABLE ) ) {
            
$request['id'] = $this->get_variation_id_from_variation_data$request$product );
        }

        
// Now we have a variation ID, get the valid set of attributes for this variation. They will have an attribute_ prefix since they are from meta.
        
$expected_attributes wc_get_product_variation_attributes$request['id'] );
        
$missing_attributes  = [];

        foreach ( 
$variable_product_attributes as $attribute ) {
            if ( ! 
$attribute['is_variation'] ) {
                continue;
            }

            
$prefixed_attribute_name 'attribute_' sanitize_title$attribute['name'] );
            
$expected_value          = isset( $expected_attributes$prefixed_attribute_name ] ) ? $expected_attributes$prefixed_attribute_name ] : '';
            
$attribute_label         wc_attribute_label$attribute['name'] );

            if ( isset( 
$request['variation'][ wc_variation_attribute_name$attribute['name'] ) ] ) ) {
                
$given_value $request['variation'][ wc_variation_attribute_name$attribute['name'] ) ];

                if ( 
$expected_value === $given_value ) {
                    continue;
                }

                
// If valid values are empty, this is an 'any' variation so get all possible values.
                
if ( '' === $expected_value && in_array$given_value$attribute->get_slugs(), true ) ) {
                    continue;
                }

                throw new 
RouteException(
                    
'woocommerce_rest_invalid_variation_data',
                    
/* translators: %1$s: Attribute name, %2$s: Allowed values. */
                    
sprintf__'Invalid value posted for %1$s. Allowed values: %2$s''woocommerce' ), $attribute_labelimplode', '$attribute->get_slugs() ) ),
                    
400
                
);
            }

            
// Fills request array with unspecified attributes that have default values. This ensures the variation always has full data.
            
if ( '' !== $expected_value && ! isset( $request['variation'][ wc_variation_attribute_name$attribute['name'] ) ] ) ) {
                
$request['variation'][ wc_variation_attribute_name$attribute['name'] ) ] = $expected_value;
            }

            
// If no attribute was posted, only error if the variation has an 'any' attribute which requires a value.
            
if ( '' === $expected_value ) {
                
$missing_attributes[] = $attribute_label;
            }
        }

        if ( ! empty( 
$missing_attributes ) ) {
            throw new 
RouteException(
                
'woocommerce_rest_missing_variation_data',
                
/* translators: %s: Attribute name. */
                
__'Missing variation data for variable product.''woocommerce' ) . ' ' sprintf_n'%s is a required field''%s are required fields'count$missing_attributes ), 'woocommerce' ), wc_format_list_of_items$missing_attributes ) ),
                
400
            
);
        }

        
ksort$request['variation'] );

        return 
$request;
    }

    
/**
     * Try to match request data to a variation ID and return the ID.
     *
     * @throws RouteException Exception if variation cannot be found.
     *
     * @param array       $request Add to cart request params.
     * @param \WC_Product $product Product being added to the cart.
     * @return int Matching variation ID.
     */
    
protected function get_variation_id_from_variation_data$request$product ) {
        
$data_store       \WC_Data_Store::load'product' );
        
$match_attributes $request['variation'];
        
$variation_id     $data_store->find_matching_product_variation$product$match_attributes );

        if ( empty( 
$variation_id ) ) {
            throw new 
RouteException(
                
'woocommerce_rest_variation_id_from_variation_data',
                
__'No matching variation found.''woocommerce' ),
                
400
            
);
        }

        return 
$variation_id;
    }

    
/**
     * Format and sanitize variation data posted to the API.
     *
     * Labels are converted to names (e.g. Size to pa_size), and values are cleaned.
     *
     * @throws RouteException Exception if variation cannot be found.
     *
     * @param array $variation_data Key value pairs of attributes and values.
     * @param array $variable_product_attributes Product attributes we're expecting.
     * @return array
     */
    
protected function sanitize_variation_data$variation_data$variable_product_attributes ) {
        
$return = [];

        foreach ( 
$variable_product_attributes as $attribute ) {
            if ( ! 
$attribute['is_variation'] ) {
                continue;
            }

            
$attribute_label           wc_attribute_label$attribute['name'] );
            
$lowercase_attribute_label strtolower$attribute_label );
            
$variation_attribute_name  wc_variation_attribute_name$attribute['name'] );

            
// Attribute labels e.g. Size.
            
if ( isset( $variation_data$attribute_label ] ) || isset( $variation_data$lowercase_attribute_label ] ) ) {

                
// Check both the original and lowercase attribute label.
                
$attribute_label = isset( $variation_data$attribute_label ] ) ? $attribute_label $lowercase_attribute_label;

                
$return$variation_attribute_name ] =
                    
$attribute['is_taxonomy']
                        ?
                        
sanitize_title$variation_data$attribute_label ] )
                        :
                        
html_entity_decode(
                            
wc_clean$variation_data$attribute_label ] ),
                            
ENT_QUOTES,
                            
get_bloginfo'charset' )
                        );
                continue;
            }

            
// Attribute slugs e.g. pa_size.
            
if ( isset( $variation_data$attribute['name'] ] ) ) {
                
$return$variation_attribute_name ] =
                    
$attribute['is_taxonomy']
                        ?
                        
sanitize_title$variation_data$attribute['name'] ] )
                        :
                        
html_entity_decode(
                            
wc_clean$variation_data$attribute['name'] ] ),
                            
ENT_QUOTES,
                            
get_bloginfo'charset' )
                        );
            }
        }
        return 
$return;
    }

    
/**
     * Get product attributes from the variable product (which may be the parent if the product object is a variation).
     *
     * @throws RouteException Exception if product is invalid.
     *
     * @param \WC_Product $product Product being added to the cart.
     * @return array
     */
    
protected function get_variable_product_attributes$product ) {
        if ( 
$product->is_typeProductType::VARIATION ) ) {
            
$product wc_get_product$product->get_parent_id() );
        }

        if ( ! 
$product || ProductStatus::TRASH === $product->get_status() ) {
            throw new 
RouteException(
                
'woocommerce_rest_cart_invalid_parent_product',
                
__'This product cannot be added to the cart.''woocommerce' ),
                
400
            
);
        }

        return 
$product->get_attributes();
    }
}