Completed
Pull Request — master (#9826)
by Mike
10:01
created

WC_Shipping::load_shipping_methods()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 18
rs 9.4286
cc 2
eloc 8
nc 2
nop 1
1
<?php
1 ignored issue
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 18 and the first side effect is on line 15.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * WooCommerce Shipping Class
4
 *
5
 * Handles shipping and loads shipping methods via hooks.
6
 *
7
 * @class 		WC_Shipping
8
 * @version		2.3.0
9
 * @package		WooCommerce/Classes/Shipping
10
 * @category	Class
11
 * @author 		WooThemes
12
 */
13
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit; // Exit if accessed directly
16
}
17
18
class WC_Shipping {
19
20
	/** @var bool True if shipping is enabled. */
21
	public $enabled					= false;
22
23
	/** @var array Stores methods loaded into woocommerce. */
24
	public $shipping_methods;
25
26
	/** @var float Stores the cost of shipping */
27
	public $shipping_total 			= 0;
28
29
	/**  @var array Stores an array of shipping taxes. */
30
	public $shipping_taxes			= array();
31
32
	/** @var array Stores the shipping classes. */
33
	public $shipping_classes		= array();
34
35
	/** @var array Stores packages to ship and to get quotes for. */
36
	public $packages				= array();
37
38
	/**
39
	 * @var WC_Shipping The single instance of the class
40
	 * @since 2.1
41
	 */
42
	protected static $_instance = null;
43
44
	/**
45
	 * Main WC_Shipping Instance.
46
	 *
47
	 * Ensures only one instance of WC_Shipping is loaded or can be loaded.
48
	 *
49
	 * @since 2.1
50
	 * @static
51
	 * @return WC_Shipping Main instance
52
	 */
53
	public static function instance() {
54
		if ( is_null( self::$_instance ) ) {
55
			self::$_instance = new self();
56
		}
57
		return self::$_instance;
58
	}
59
60
	/**
61
	 * Cloning is forbidden.
62
	 *
63
	 * @since 2.1
64
	 */
65
	public function __clone() {
66
		_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'woocommerce' ), '2.1' );
67
	}
68
69
	/**
70
	 * Unserializing instances of this class is forbidden.
71
	 *
72
	 * @since 2.1
73
	 */
74
	public function __wakeup() {
75
		_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'woocommerce' ), '2.1' );
76
	}
77
78
	/**
79
	 * Initialize shipping.
80
	 */
81
	public function __construct() {
82
		$this->init();
83
	}
84
85
    /**
86
     * init function.
87
     */
88
    public function init() {
89
		do_action( 'woocommerce_shipping_init' );
90
91
		$this->enabled = ( get_option('woocommerce_calc_shipping') == 'no' ) ? false : true;
92
	}
93
94
	/**
95
	 * Shipping methods register themselves by returning their main class name through the woocommerce_shipping_methods filter.
96
	 * @return array
97
	 */
98
	public function get_shipping_method_class_names() {
99
		// Unique Method ID => Method Class name
100
		return apply_filters( 'woocommerce_shipping_methods', array(
101
			'flat_rate'              => 'WC_Shipping_Flat_Rate',
102
			'free_shipping'          => 'WC_Shipping_Free_Shipping',
103
			'international_delivery' => 'WC_Shipping_International_Delivery',
104
			'local_delivery'         => 'WC_Shipping_Local_Delivery',
105
			'local_pickup'           => 'WC_Shipping_Local_Pickup'
106
		) );
107
	}
108
109
	/**
110
	 * load_shipping_methods function.
111
	 *
112
	 * Loads all shipping methods which are hooked in. If a $package is passed some methods may add themselves conditionally.
113
	 *
114
	 * Methods are sorted into their user-defined order after being loaded.
115
	 *
116
	 * @access public
117
	 * @param array $package
118
	 * @return array
119
	 */
120
	public function load_shipping_methods( $package = array() ) {
121
122
		$this->unregister_shipping_methods();
123
124
		// Methods can register themselves through this hook
125
		do_action( 'woocommerce_load_shipping_methods', $package );
126
127
		// Register methods through a filter
128
		$shipping_methods_to_load = $this->get_shipping_method_class_names();
129
130
		foreach ( $shipping_methods_to_load as $method ) {
131
			$this->register_shipping_method( $method );
132
		}
133
134
		$this->sort_shipping_methods();
135
136
		return $this->shipping_methods;
137
	}
138
139
	/**
140
	 * Register a shipping method for use in calculations.
141
	 *
142
	 * @param object|string $method Either the name of the method's class, or an instance of the method's class
143
	 */
144
	public function register_shipping_method( $method ) {
145
		if ( ! is_object( $method ) ) {
146
			$method = new $method();
147
		}
148
149
		$id = empty( $method->instance_id ) ? $method->id : $method->instance_id;
150
151
		$this->shipping_methods[ $id ] = $method;
152
	}
153
154
	/**
155
	 * Unregister shipping methods.
156
	 */
157
	public function unregister_shipping_methods() {
158
		$this->shipping_methods = array();
159
	}
160
161
	/**
162
	 * Sort shipping methods.
163
	 *
164
	 * Sorts shipping methods into the user defined order.
165
	 *
166
	 * @return array
167
	 */
168
	public function sort_shipping_methods() {
169
170
		$sorted_shipping_methods = array();
171
172
		// Get order option
173
		$ordering 	= (array) get_option('woocommerce_shipping_method_order');
174
		$order_end 	= 999;
175
176
		// Load shipping methods in order
177
		foreach ( $this->shipping_methods as $method ) {
178
179
			if ( isset( $ordering[ $method->id ] ) && is_numeric( $ordering[ $method->id ] ) ) {
180
				// Add in position
181
				$sorted_shipping_methods[ $ordering[ $method->id ] ][] = $method;
182
			} else {
183
				// Add to end of the array
184
				$sorted_shipping_methods[ $order_end ][] = $method;
185
			}
186
		}
187
188
		ksort( $sorted_shipping_methods );
189
190
		$this->shipping_methods = array();
191
192
		foreach ( $sorted_shipping_methods as $methods )
193
			foreach ( $methods as $method ) {
194
				$id = empty( $method->instance_id ) ? $method->id : $method->instance_id;
195
				$this->shipping_methods[ $id ] = $method;
196
			}
197
198
		return $this->shipping_methods;
199
	}
200
201
	/**
202
	 * get_shipping_methods function.
203
	 *
204
	 * Returns all registered shipping methods for usage.
205
	 *
206
	 * @access public
207
	 * @return array
208
	 */
209
	public function get_shipping_methods() {
210
		if ( is_null( $this->shipping_methods ) ) {
211
			$this->load_shipping_methods();
212
		}
213
		return $this->shipping_methods;
214
	}
215
216
	/**
217
	 * get_shipping_classes function.
218
	 *
219
	 * Load shipping classes taxonomy terms.
220
	 *
221
	 * @access public
222
	 * @return array
223
	 */
224
	public function get_shipping_classes() {
225
		if ( empty( $this->shipping_classes ) ) {
226
			$classes                = get_terms( 'product_shipping_class', array( 'hide_empty' => '0' ) );
227
			$this->shipping_classes = $classes && ! is_wp_error( $classes ) ? $classes : array();
228
		}
229
		return $this->shipping_classes;
230
	}
231
232
	/**
233
	 * Get the default method.
234
	 * @param  array  $available_methods
235
	 * @param  boolean $current_chosen_method
236
	 * @return string
237
	 */
238
	private function get_default_method( $available_methods, $current_chosen_method = false ) {
239
		$selection_priority = get_option( 'woocommerce_shipping_method_selection_priority', array() );
240
241
		if ( ! empty( $available_methods ) ) {
242
243
			// Is a method already chosen?
244
			if ( ! empty( $current_chosen_method ) && ! isset( $available_methods[ $current_chosen_method ] ) ) {
245
				foreach ( $available_methods as $method_key => $method ) {
246
					if ( strpos( $method->id, $current_chosen_method ) === 0 ) {
247
						return $method->id;
248
					}
249
				}
250
			}
251
252
			// Order by priorities and costs
253
			$prioritized_methods = array();
254
255
			foreach ( $available_methods as $method_key => $method ) {
256
				// Some IDs contain : if they have multiple rates so use $method->method_id
257
				$priority  = isset( $selection_priority[ $method->method_id ] ) ? absint( $selection_priority[ $method->method_id ] ): 1;
258
259
				if ( empty( $prioritized_methods[ $priority ] ) ) {
260
					$prioritized_methods[ $priority ] = array();
261
				}
262
263
				$prioritized_methods[ $priority ][ $method_key ] = $method->cost;
264
			}
265
266
			ksort( $prioritized_methods );
267
			$prioritized_methods = current( $prioritized_methods );
268
			asort( $prioritized_methods );
269
270
			return current( array_keys( $prioritized_methods ) );
271
		}
272
273
		return false;
274
	}
275
276
	/**
277
	 * calculate_shipping function.
278
	 *
279
	 * Calculate shipping for (multiple) packages of cart items.
280
	 *
281
	 * @param array $packages multi-dimensional array of cart items to calc shipping for
282
	 */
283
	public function calculate_shipping( $packages = array() ) {
284
		$this->shipping_total = null;
285
		$this->shipping_taxes = array();
286
		$this->packages       = array();
287
288
		if ( ! $this->enabled || empty( $packages ) ) {
289
			return;
290
		}
291
292
		// Calculate costs for passed packages
293
		$package_keys 		= array_keys( $packages );
294
		$package_keys_size 	= sizeof( $package_keys );
295
296
		for ( $i = 0; $i < $package_keys_size; $i ++ ) {
297
			$this->packages[ $package_keys[ $i ] ] = $this->calculate_shipping_for_package( $packages[ $package_keys[ $i ] ] );
298
		}
299
300
		// Get all chosen methods
301
		$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
302
		$method_counts  = WC()->session->get( 'shipping_method_counts' );
303
304
		// Get chosen methods for each package
305
		foreach ( $this->packages as $i => $package ) {
306
			$chosen_method    = false;
307
			$method_count     = false;
308
309
			if ( ! empty( $chosen_methods[ $i ] ) ) {
310
				$chosen_method = $chosen_methods[ $i ];
311
			}
312
313
			if ( ! empty( $method_counts[ $i ] ) ) {
314
				$method_count = $method_counts[ $i ];
315
			}
316
317
			// Get available methods for package
318
			$available_methods = $package['rates'];
319
320
			if ( sizeof( $available_methods ) > 0 ) {
321
322
				// If not set, not available, or available methods have changed, set to the DEFAULT option
323
				if ( empty( $chosen_method ) || ! isset( $available_methods[ $chosen_method ] ) || $method_count != sizeof( $available_methods ) ) {
324
					$chosen_method        = apply_filters( 'woocommerce_shipping_chosen_method', $this->get_default_method( $available_methods, $chosen_method ), $available_methods );
325
					$chosen_methods[ $i ] = $chosen_method;
326
					$method_counts[ $i ]  = sizeof( $available_methods );
327
					do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
328
				}
329
330
				// Store total costs
331
				if ( $chosen_method ) {
332
					$rate = $available_methods[ $chosen_method ];
333
334
					// Merge cost and taxes - label and ID will be the same
335
					$this->shipping_total += $rate->cost;
336
337
					if ( ! empty( $rate->taxes ) && is_array( $rate->taxes ) ) {
338 View Code Duplication
						foreach ( array_keys( $this->shipping_taxes + $rate->taxes ) as $key ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
339
							$this->shipping_taxes[ $key ] = ( isset( $rate->taxes[$key] ) ? $rate->taxes[$key] : 0 ) + ( isset( $this->shipping_taxes[$key] ) ? $this->shipping_taxes[$key] : 0 );
340
						}
341
					}
342
				}
343
			}
344
		}
345
346
		// Save all chosen methods (array)
347
		WC()->session->set( 'chosen_shipping_methods', $chosen_methods );
348
		WC()->session->set( 'shipping_method_counts', $method_counts );
349
	}
350
351
	/**
352
	 * Calculate shipping rates for a package,
353
	 *
354
	 * Calculates each shipping methods cost. Rates are stored in the session based on the package hash to avoid re-calculation every page load.
355
	 *
356
	 * @param array $package cart items
357
	 * @return array
358
	 */
359
	public function calculate_shipping_for_package( $package = array() ) {
360
		if ( ! $this->enabled || ! $package ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $package of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
361
			return false;
362
		}
363
364
		// Check if we need to recalculate shipping for this package
365
		$package_hash   = 'wc_ship_' . md5( json_encode( $package ) . WC_Cache_Helper::get_transient_version( 'shipping' ) );
366
		$status_options = get_option( 'woocommerce_status_options', array() );
367
		$stored_rates   = WC()->session->get( 'shipping_for_package' );
368
369
		if ( ! is_array( $stored_rates ) || $package_hash !== $stored_rates['package_hash'] || ! empty( $status_options['shipping_debug_mode'] ) ) {
370
			// Calculate shipping method rates
371
			$package['rates'] = array();
372
373
			foreach ( $this->load_shipping_methods( $package ) as $shipping_method ) {
374
				if ( $shipping_method->is_available( $package ) && ( empty( $package['ship_via'] ) || in_array( $shipping_method->id, $package['ship_via'] ) ) ) {
375
376
					// Reset Rates
377
					$shipping_method->rates = array();
378
379
					// Calculate Shipping for package
380
					$shipping_method->calculate_shipping( $package );
381
382
					// Place rates in package array
383
					if ( ! empty( $shipping_method->rates ) && is_array( $shipping_method->rates ) ) {
384
						foreach ( $shipping_method->rates as $rate ) {
385
							$package['rates'][ $rate->id ] = $rate;
386
						}
387
					}
388
				}
389
			}
390
391
			// Filter the calculated rates
392
			$package['rates'] = apply_filters( 'woocommerce_package_rates', $package['rates'], $package );
393
394
			// Store in session to avoid recalculation
395
			WC()->session->set( 'shipping_for_package', array(
396
				'package_hash' => $package_hash,
397
				'rates'        => $package['rates']
398
			) );
399
		} else {
400
			$package['rates'] = $stored_rates['rates'];
401
		}
402
403
		return $package;
404
	}
405
406
	/**
407
	 * Get packages.
408
	 *
409
	 * @return array
410
	 */
411
	public function get_packages() {
412
		return $this->packages;
413
	}
414
415
	/**
416
	 * Reset shipping.
417
	 *
418
	 * Reset the totals for shipping as a whole.
419
	 */
420
	public function reset_shipping() {
421
		unset( WC()->session->chosen_shipping_methods );
422
		$this->shipping_total = null;
423
		$this->shipping_taxes = array();
424
		$this->packages = array();
425
	}
426
427
	/**
428
	 * Process admin options.
429
	 *
430
	 * Saves options on the shipping setting page.
431
	 */
432
	public function process_admin_options() {
433
		$method_order       = isset( $_POST['method_order'] ) ? $_POST['method_order'] : '';
434
		$method_priority    = isset( $_POST['method_priority'] ) ? $_POST['method_priority'] : '';
435
		$order              = array();
436
		$selection_priority = array();
437
438
		if ( is_array( $method_order ) && sizeof( $method_order ) > 0 ) {
439
			$loop = 0;
440
			foreach ( $method_order as $method_id ) {
441
				$order[ $method_id ]              = $loop;
442
				$selection_priority[ $method_id ] = absint( $method_priority[ $method_id ] );
443
				$loop ++;
444
			}
445
		}
446
447
		update_option( 'woocommerce_shipping_method_selection_priority', $selection_priority );
448
		update_option( 'woocommerce_shipping_method_order', $order );
449
	}
450
451
}
452
453
/**
454
 * Register a shipping method.
455
 *
456
 * Registers a shipping method ready to be loaded. Accepts a class name (string) or a class object.
457
 *
458
 * @package		WooCommerce/Classes/Shipping
459
 * @since 1.5.7
460
 */
461
function woocommerce_register_shipping_method( $shipping_method ) {
462
	WC()->shipping->register_shipping_method( $shipping_method );
463
}
464