WC_Cart_Session::populate_cart_from_order()   F
last analyzed

Complexity

Conditions 18
Paths 113

Size

Total Lines 98

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 0
Metric Value
cc 18
nc 113
nop 2
dl 0
loc 98
ccs 0
cts 60
cp 0
crap 342
rs 3.8503
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Cart session handling class.
4
 *
5
 * @package WooCommerce/Classes
6
 * @version 3.2.0
7
 */
8
9
if ( ! defined( 'ABSPATH' ) ) {
10
	exit;
11
}
12
13
/**
14
 * WC_Cart_Session class.
15
 *
16
 * @since 3.2.0
17
 */
18
final class WC_Cart_Session {
19
20
	/**
21
	 * Reference to cart object.
22
	 *
23
	 * @since 3.2.0
24
	 * @var WC_Cart
25
	 */
26
	protected $cart;
27
28
	/**
29
	 * Sets up the items provided, and calculate totals.
30
	 *
31
	 * @since 3.2.0
32
	 * @throws Exception If missing WC_Cart object.
33
	 *
34
	 * @param WC_Cart $cart Cart object to calculate totals for.
35
	 */
36 2
	public function __construct( &$cart ) {
37 2
		if ( ! is_a( $cart, 'WC_Cart' ) ) {
38
			throw new Exception( 'A valid WC_Cart object is required' );
39
		}
40
41 2
		$this->cart = $cart;
42
	}
43
44
	/**
45
	 * Register methods for this object on the appropriate WordPress hooks.
46
	 */
47 2
	public function init() {
48 2
		add_action( 'wp_loaded', array( $this, 'get_cart_from_session' ) );
49 2
		add_action( 'woocommerce_cart_emptied', array( $this, 'destroy_cart_session' ) );
50 2
		add_action( 'woocommerce_after_calculate_totals', array( $this, 'set_session' ) );
51 2
		add_action( 'woocommerce_cart_loaded_from_session', array( $this, 'set_session' ) );
52 2
		add_action( 'woocommerce_removed_coupon', array( $this, 'set_session' ) );
53
54
		// Persistent cart stored to usermeta.
55 2
		add_action( 'woocommerce_add_to_cart', array( $this, 'persistent_cart_update' ) );
56 2
		add_action( 'woocommerce_cart_item_removed', array( $this, 'persistent_cart_update' ) );
57 2
		add_action( 'woocommerce_cart_item_restored', array( $this, 'persistent_cart_update' ) );
58 2
		add_action( 'woocommerce_cart_item_set_quantity', array( $this, 'persistent_cart_update' ) );
59
60
		// Cookie events - cart cookies need to be set before headers are sent.
61 2
		add_action( 'woocommerce_add_to_cart', array( $this, 'maybe_set_cart_cookies' ) );
62 2
		add_action( 'wp', array( $this, 'maybe_set_cart_cookies' ), 99 );
63 2
		add_action( 'shutdown', array( $this, 'maybe_set_cart_cookies' ), 0 );
64
	}
65
66
	/**
67
	 * Get the cart data from the PHP session and store it in class variables.
68
	 *
69
	 * @since 3.2.0
70
	 */
71
	public function get_cart_from_session() {
72
		do_action( 'woocommerce_load_cart_from_session' );
73
		$this->cart->set_totals( WC()->session->get( 'cart_totals', null ) );
74
		$this->cart->set_applied_coupons( WC()->session->get( 'applied_coupons', array() ) );
75
		$this->cart->set_coupon_discount_totals( WC()->session->get( 'coupon_discount_totals', array() ) );
76
		$this->cart->set_coupon_discount_tax_totals( WC()->session->get( 'coupon_discount_tax_totals', array() ) );
77
		$this->cart->set_removed_cart_contents( WC()->session->get( 'removed_cart_contents', array() ) );
78
79
		$update_cart_session = false; // Flag to indicate the stored cart should be updated.
80
		$order_again         = false; // Flag to indicate whether this is a re-order.
81
		$cart                = WC()->session->get( 'cart', null );
82
		$merge_saved_cart    = (bool) get_user_meta( get_current_user_id(), '_woocommerce_load_saved_cart_after_login', true );
83
84
		// Merge saved cart with current cart.
85
		if ( is_null( $cart ) || $merge_saved_cart ) {
86
			$saved_cart          = $this->get_saved_cart();
87
			$cart                = is_null( $cart ) ? array() : $cart;
88
			$cart                = array_merge( $saved_cart, $cart );
89
			$update_cart_session = true;
90
91
			delete_user_meta( get_current_user_id(), '_woocommerce_load_saved_cart_after_login' );
92
		}
93
94
		// Populate cart from order.
95
		if ( isset( $_GET['order_again'], $_GET['_wpnonce'] ) && is_user_logged_in() && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-order_again' ) ) { // WPCS: input var ok, sanitization ok.
96
			$cart        = $this->populate_cart_from_order( absint( $_GET['order_again'] ), $cart ); // WPCS: input var ok.
97
			$order_again = true;
98
		}
99
100
		// Prime caches to reduce future queries.
101
		if ( is_callable( '_prime_post_caches' ) ) {
102
			_prime_post_caches( wp_list_pluck( $cart, 'product_id' ) );
103
		}
104
105
		$cart_contents = array();
106
107
		foreach ( $cart as $key => $values ) {
108
			if ( ! is_customize_preview() && 'customize-preview' === $key ) {
109
				continue;
110
			}
111
112
			$product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );
113
114
			if ( empty( $product ) || ! $product->exists() || 0 >= $values['quantity'] ) {
115
				continue;
116
			}
117
118
			/**
119
			 * Allow 3rd parties to validate this item before it's added to cart and add their own notices.
120
			 *
121
			 * @since 3.6.0
122
			 *
123
			 * @param bool $remove_cart_item_from_session If true, the item will not be added to the cart. Default: false.
124
			 * @param string $key Cart item key.
125
			 * @param array $values Cart item values e.g. quantity and product_id.
126
			 */
127
			if ( apply_filters( 'woocommerce_pre_remove_cart_item_from_session', false, $key, $values ) ) {
128
				$update_cart_session = true;
129
				do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
130
131
			} elseif ( ! $product->is_purchasable() ) {
132
				$update_cart_session = true;
133
				/* translators: %s: product name */
134
				$message = sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $product->get_name() );
135
				/**
136
				 * Filter message about item removed from the cart.
137
				 *
138
				 * @since 3.8.0
139
				 * @param string     $message Message.
140
				 * @param WC_Product $product Product data.
141
				 */
142
				$message = apply_filters( 'woocommerce_cart_item_removed_message', $message, $product );
143
				wc_add_notice( $message, 'error' );
144
				do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
145
146
			} elseif ( ! empty( $values['data_hash'] ) && ! hash_equals( $values['data_hash'], wc_get_cart_item_data_hash( $product ) ) ) { // phpcs:ignore PHPCompatibility.PHP.NewFunctions.hash_equalsFound
147
				$update_cart_session = true;
148
				/* translators: %1$s: product name. %2$s product permalink */
149
				wc_add_notice( sprintf( __( '%1$s has been removed from your cart because it has since been modified. You can add it back to your cart <a href="%2$s">here</a>.', 'woocommerce' ), $product->get_name(), $product->get_permalink() ), 'notice' );
150
				do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
151
152
			} else {
153
				// Put session data into array. Run through filter so other plugins can load their own session data.
154
				$session_data = array_merge(
155
					$values,
156
					array(
157
						'data' => $product,
158
					)
159
				);
160
161
				$cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
162
163
				// Add to cart right away so the product is visible in woocommerce_get_cart_item_from_session hook.
164
				$this->cart->set_cart_contents( $cart_contents );
165
			}
166
		}
167
168
		// If it's not empty, it's been already populated by the loop above.
169
		if ( ! empty( $cart_contents ) ) {
170
			$this->cart->set_cart_contents( apply_filters( 'woocommerce_cart_contents_changed', $cart_contents ) );
171
		}
172
173
		do_action( 'woocommerce_cart_loaded_from_session', $this->cart );
174
175
		if ( $update_cart_session || is_null( WC()->session->get( 'cart_totals', null ) ) ) {
176
			WC()->session->set( 'cart', $this->get_cart_for_session() );
177
			$this->cart->calculate_totals();
178
		}
179
180
		// If this is a re-order, redirect to the cart page to get rid of the `order_again` query string.
181
		if ( $order_again ) {
182
			wp_safe_redirect( wc_get_cart_url() );
183
			exit;
184
		}
185
	}
186
187
	/**
188
	 * Destroy cart session data.
189
	 *
190
	 * @since 3.2.0
191
	 */
192 101
	public function destroy_cart_session() {
193 101
		WC()->session->set( 'cart', null );
194 101
		WC()->session->set( 'cart_totals', null );
195 101
		WC()->session->set( 'applied_coupons', null );
196 101
		WC()->session->set( 'coupon_discount_totals', null );
197 101
		WC()->session->set( 'coupon_discount_tax_totals', null );
198 101
		WC()->session->set( 'removed_cart_contents', null );
199 101
		WC()->session->set( 'order_awaiting_payment', null );
200
	}
201
202
	/**
203
	 * Will set cart cookies if needed and when possible.
204
	 *
205
	 * @since 3.2.0
206
	 */
207 82
	public function maybe_set_cart_cookies() {
208 82
		if ( ! headers_sent() && did_action( 'wp_loaded' ) ) {
209
			if ( ! $this->cart->is_empty() ) {
210
				$this->set_cart_cookies( true );
211
			} elseif ( isset( $_COOKIE['woocommerce_items_in_cart'] ) ) { // WPCS: input var ok.
212
				$this->set_cart_cookies( false );
213
			}
214
		}
215
	}
216
217
	/**
218
	 * Sets the php session data for the cart and coupons.
219
	 */
220 92
	public function set_session() {
221 92
		WC()->session->set( 'cart', $this->get_cart_for_session() );
222 92
		WC()->session->set( 'cart_totals', $this->cart->get_totals() );
223 92
		WC()->session->set( 'applied_coupons', $this->cart->get_applied_coupons() );
224 92
		WC()->session->set( 'coupon_discount_totals', $this->cart->get_coupon_discount_totals() );
225 92
		WC()->session->set( 'coupon_discount_tax_totals', $this->cart->get_coupon_discount_tax_totals() );
226 92
		WC()->session->set( 'removed_cart_contents', $this->cart->get_removed_cart_contents() );
227
228 92
		do_action( 'woocommerce_cart_updated' );
229
	}
230
231
	/**
232
	 * Returns the contents of the cart in an array without the 'data' element.
233
	 *
234
	 * @return array contents of the cart
235
	 */
236 92
	public function get_cart_for_session() {
237 92
		$cart_session = array();
238
239 92
		foreach ( $this->cart->get_cart() as $key => $values ) {
240 82
			$cart_session[ $key ] = $values;
241 82
			unset( $cart_session[ $key ]['data'] ); // Unset product object.
242
		}
243
244 92
		return $cart_session;
245
	}
246
247
	/**
248
	 * Save the persistent cart when the cart is updated.
249
	 */
250 82
	public function persistent_cart_update() {
251 82
		if ( get_current_user_id() && apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
252
			update_user_meta(
253
				get_current_user_id(),
254
				'_woocommerce_persistent_cart_' . get_current_blog_id(),
255
				array(
256
					'cart' => $this->get_cart_for_session(),
257
				)
258
			);
259
		}
260
	}
261
262
	/**
263
	 * Delete the persistent cart permanently.
264
	 */
265 100
	public function persistent_cart_destroy() {
266 100
		if ( get_current_user_id() && apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
267
			delete_user_meta( get_current_user_id(), '_woocommerce_persistent_cart_' . get_current_blog_id() );
268
		}
269
	}
270
271
	/**
272
	 * Set cart hash cookie and items in cart if not already set.
273
	 *
274
	 * @param bool $set Should cookies be set (true) or unset.
275
	 */
276
	private function set_cart_cookies( $set = true ) {
277
		if ( $set ) {
278
			$setcookies = array(
279
				'woocommerce_items_in_cart' => '1',
280
				'woocommerce_cart_hash'     => WC()->cart->get_cart_hash(),
281
			);
282
			foreach ( $setcookies as $name => $value ) {
283
				if ( ! isset( $_COOKIE[ $name ] ) || $_COOKIE[ $name ] !== $value ) {
284
					wc_setcookie( $name, $value );
285
				}
286
			}
287
		} else {
288
			$unsetcookies = array(
289
				'woocommerce_items_in_cart',
290
				'woocommerce_cart_hash',
291
			);
292
			foreach ( $unsetcookies as $name ) {
293
				if ( isset( $_COOKIE[ $name ] ) ) {
294
					wc_setcookie( $name, 0, time() - HOUR_IN_SECONDS );
295
					unset( $_COOKIE[ $name ] );
296
				}
297
			}
298
		}
299
300
		do_action( 'woocommerce_set_cart_cookies', $set );
301
	}
302
303
	/**
304
	 * Get the persistent cart from the database.
305
	 *
306
	 * @since  3.5.0
307
	 * @return array
308
	 */
309
	private function get_saved_cart() {
310
		$saved_cart = array();
311
312
		if ( apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
313
			$saved_cart_meta = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart_' . get_current_blog_id(), true );
314
315
			if ( isset( $saved_cart_meta['cart'] ) ) {
316
				$saved_cart = array_filter( (array) $saved_cart_meta['cart'] );
317
			}
318
		}
319
320
		return $saved_cart;
321
	}
322
323
	/**
324
	 * Get a cart from an order, if user has permission.
325
	 *
326
	 * @since  3.5.0
327
	 *
328
	 * @param int   $order_id Order ID to try to load.
329
	 * @param array $cart Current cart array.
330
	 *
331
	 * @return array
332
	 */
333
	private function populate_cart_from_order( $order_id, $cart ) {
334
		$order = wc_get_order( $order_id );
335
336
		if ( ! $order->get_id() || ! $order->has_status( apply_filters( 'woocommerce_valid_order_statuses_for_order_again', array( 'completed' ) ) ) || ! current_user_can( 'order_again', $order->get_id() ) ) {
337
			return;
338
		}
339
340
		if ( apply_filters( 'woocommerce_empty_cart_when_order_again', true ) ) {
341
			$cart = array();
342
		}
343
344
		$inital_cart_size = count( $cart );
345
		$order_items      = $order->get_items();
346
347
		foreach ( $order_items as $item ) {
348
			$product_id     = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $item->get_product_id() );
349
			$quantity       = $item->get_quantity();
350
			$variation_id   = (int) $item->get_variation_id();
351
			$variations     = array();
352
			$cart_item_data = apply_filters( 'woocommerce_order_again_cart_item_data', array(), $item, $order );
353
			$product        = $item->get_product();
354
355
			if ( ! $product ) {
356
				continue;
357
			}
358
359
			// Prevent reordering variable products if no selected variation.
360
			if ( ! $variation_id && $product->is_type( 'variable' ) ) {
361
				continue;
362
			}
363
364
			// Prevent reordering items specifically out of stock.
365
			if ( ! $product->is_in_stock() ) {
366
				continue;
367
			}
368
369
			foreach ( $item->get_meta_data() as $meta ) {
370
				if ( taxonomy_is_product_attribute( $meta->key ) ) {
371
					$term                     = get_term_by( 'slug', $meta->value, $meta->key );
372
					$variations[ $meta->key ] = $term ? $term->name : $meta->value;
373
				} elseif ( meta_is_product_attribute( $meta->key, $meta->value, $product_id ) ) {
374
					$variations[ $meta->key ] = $meta->value;
375
				}
376
			}
377
378
			if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data ) ) {
379
				continue;
380
			}
381
382
			// Add to cart directly.
383
			$cart_id          = WC()->cart->generate_cart_id( $product_id, $variation_id, $variations, $cart_item_data );
384
			$product_data     = wc_get_product( $variation_id ? $variation_id : $product_id );
385
			$cart[ $cart_id ] = apply_filters(
386
				'woocommerce_add_order_again_cart_item',
387
				array_merge(
388
					$cart_item_data,
389
					array(
390
						'key'          => $cart_id,
391
						'product_id'   => $product_id,
392
						'variation_id' => $variation_id,
393
						'variation'    => $variations,
394
						'quantity'     => $quantity,
395
						'data'         => $product_data,
396
						'data_hash'    => wc_get_cart_item_data_hash( $product_data ),
0 ignored issues
show
Documentation introduced by
$product_data is of type false|object, but the function expects a object<WC_Product>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
397
					)
398
				),
399
				$cart_id
400
			);
401
		}
402
403
		do_action_ref_array( 'woocommerce_ordered_again', array( $order->get_id(), $order_items, &$cart ) );
404
405
		$num_items_in_cart           = count( $cart );
406
		$num_items_in_original_order = count( $order_items );
407
		$num_items_added             = $num_items_in_cart - $inital_cart_size;
408
409
		if ( $num_items_in_original_order > $num_items_added ) {
410
			wc_add_notice(
411
				sprintf(
412
					/* translators: %d item count */
413
					_n(
414
						'%d item from your previous order is currently unavailable and could not be added to your cart.',
415
						'%d items from your previous order are currently unavailable and could not be added to your cart.',
416
						$num_items_in_original_order - $num_items_added,
417
						'woocommerce'
418
					),
419
					$num_items_in_original_order - $num_items_added
420
				),
421
				'error'
422
			);
423
		}
424
425
		if ( 0 < $num_items_added ) {
426
			wc_add_notice( __( 'The cart has been filled with the items from your previous order.', 'woocommerce' ) );
427
		}
428
429
		return $cart;
430
	}
431
}
432