Completed
Pull Request — master (#9826)
by Mike
21:27
created

WC_Shipping_Method::get_taxes_per_item()   C

Complexity

Conditions 11
Paths 3

Size

Total Lines 34
Code Lines 15

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 34
rs 5.2653
cc 11
eloc 15
nc 3
nop 1

How to fix   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
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 4.

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
if ( ! defined( 'ABSPATH' ) ) {
4
	exit;
5
}
6
7
/**
8
 * WooCommerce Shipping Method Class.
9
 *
10
 * Extended by shipping methods to handle shipping calculations etc.
11
 *
12
 * @class       WC_Shipping_Method
13
 * @version     2.6.0
14
 * @package     WooCommerce/Abstracts
15
 * @category    Abstract Class
16
 * @author      WooThemes
17
 */
18
abstract class WC_Shipping_Method extends WC_Settings_API {
19
20
	/**
21
	 * Features this method supports. Possible features used by core:
22
	 * - shipping-zones Shipping zone functionality + instances
23
	 * - instance-settings Instance settings screens.
24
	 * - settings Non-instance settings screens. Enabled by default for BW compatibility with methods before instances existed.
25
	 * @var array
26
	 */
27
	public $supports             = array( 'settings' );
28
29
	/**
30
	 * Unique ID for the shipping method - must be set.
31
	 * @var string
32
	 */
33
	public $id                   = '';
34
35
	/**
36
	 * Method title.
37
	 * @var string
38
	 */
39
	public $method_title         = '';
40
41
	/**
42
	 * Method description.
43
	 * @var string
44
	 */
45
	public $method_description   = '';
46
47
	/**
48
	 * yes or no based on whether the method is enabled.
49
	 * @var string
50
	 */
51
	public $enabled              = 'yes';
52
53
	/**
54
	 * Shipping method title for the frontend.
55
	 * @var string
56
	 */
57
	public $title;
58
59
	/**
60
	 * This is an array of rates - methods must populate this array to register shipping costs.
61
	 * @var array
62
	 */
63
	public $rates                = array();
64
65
	/**
66
	 * If 'taxable' tax will be charged for this method (if applicable).
67
	 * @var string
68
	 */
69
	public $tax_status           = 'taxable';
70
71
	/**
72
	 * Fee for the method (if applicable).
73
	 * @var string
74
	 */
75
	public $fee                  = null;
76
77
	/** @var float Minimum fee for the method */
78
	/**
79
	 * Minimum fee for the method (if applicable).
80
	 * @var string
81
	 */
82
	public $minimum_fee          = null;
83
84
	/**
85
	 * Availability - legacy. Used for method Availability.
86
	 * No longer useful for instance based shipping methods.
87
	 * @deprecated 2.6.0
88
	 * @var string
89
	 */
90
	public $availability;
91
92
	/**
93
	 * Availability countries - legacy. Used for method Availability.
94
	 * No longer useful for instance based shipping methods.
95
	 * @deprecated 2.6.0
96
	 * @var string
97
	 */
98
	public $countries            = array();
99
100
	/**
101
	 * Instance ID if used.
102
	 * @var int
103
	 */
104
	public $instance_id          = 0;
105
106
	/**
107
	 * Instance form fields.
108
	 * @var array
109
	 */
110
	public $instance_form_fields = array();
111
112
	/**
113
	 * Instance settings.
114
	 * @var array
115
	 */
116
	public $instance_settings    = array();
117
118
	/**
119
	 * Constructor.
120
	 * @param int $instance_id
121
	 */
122
	public function __construct( $instance_id = 0 ) {
123
		$this->instance_id = absint( $instance_id );
124
	}
125
126
	/**
127
	 * Check if a shipping method supports a given feature.
128
	 *
129
	 * Methods should override this to declare support (or lack of support) for a feature.
130
	 *
131
	 * @param $feature string The name of a feature to test support for.
132
	 * @return bool True if the shipping method supports the feature, false otherwise.
133
	 */
134
	public function supports( $feature ) {
135
		return apply_filters( 'woocommerce_shipping_method_supports', in_array( $feature, $this->supports ), $feature, $this );
136
	}
137
138
	/**
139
	 * Called to calculate shipping rates for this method. Rates can be added using the add_rate() method.
140
	 */
141
	public function calculate_shipping() {}
142
143
	/**
144
	 * Whether or not we need to calculate tax on top of the shipping rate.
145
	 * @return boolean
146
	 */
147
	public function is_taxable() {
148
		return wc_tax_enabled() && 'taxable' === $this->tax_status && ! WC()->customer->is_vat_exempt();
149
	}
150
151
	/**
152
	 * Whether or not this method is enabled in settings.
153
	 * @since 2.6.0
154
	 * @return boolean
155
	 */
156
	public function is_enabled() {
157
		return 'yes' === $this->enabled;
158
	}
159
160
	/**
161
	 * Return the shipping method instance ID.
162
	 * @since 2.6.0
163
	 * @return int
164
	 */
165
	public function get_instance_id() {
166
		return $this->instance_id;
167
	}
168
169
	/**
170
	 * Return the shipping method title.
171
	 * @since 2.6.0
172
	 * @return string
173
	 */
174
	public function get_method_title() {
175
		return apply_filters( 'woocommerce_shipping_method_title', $this->method_title, $this );
176
	}
177
178
	/**
179
	 * Return the shipping method description.
180
	 * @since 2.6.0
181
	 * @return string
182
	 */
183
	public function get_method_description() {
184
		return apply_filters( 'woocommerce_shipping_method_description', $this->method_description, $this );
185
	}
186
187
	/**
188
	 * Return the shipping title which is user set.
189
	 *
190
	 * @return string
191
	 */
192
	public function get_title() {
193
		return apply_filters( 'woocommerce_shipping_method_title', $this->title, $this->id );
194
	}
195
196
	/**
197
	 * Return calculated rates for a package.
198
	 * @since 2.6.0
199
	 * @param object $package
200
	 * @return array
201
	 */
202
	public function get_rates_for_package( $package ) {
203
		$this->rates = array();
204
		if ( $this->is_available( $package ) && ( empty( $package['ship_via'] ) || in_array( $this->id, $package['ship_via'] ) ) ) {
0 ignored issues
show
Documentation introduced by
$package is of type object, but the function expects a array.

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...
205
			$this->calculate_shipping( $package );
0 ignored issues
show
Unused Code introduced by
The call to WC_Shipping_Method::calculate_shipping() has too many arguments starting with $package.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
206
		}
207
		return $this->rates;
208
	}
209
210
	/**
211
	 * Add a shipping rate. If taxes are not set they will be calculated based on cost.
212
	 * @param array $args (default: array())
213
	 */
214
	public function add_rate( $args = array() ) {
215
		$args = wp_parse_args( $args, array(
216
			'id'        => '',          // ID for the rate
217
			'label'     => '',          // Label for the rate
218
			'cost'      => '0',         // Amount or array of costs (per item shipping)
219
			'taxes'     => '',          // Pass taxes, nothing to have it calculated for you, or 'false' to calc no tax
220
			'calc_tax'  => 'per_order'  // Calc tax per_order or per_item. Per item needs an array of costs
221
		) );
222
223
		// ID and label are required
224
		if ( ! $args['id'] || ! $args['label'] ) {
225
			return;
226
		}
227
228
		// Handle cost
229
		$total_cost = is_array( $args['cost'] ) ? array_sum( $args['cost'] ) : $args['cost'];
230
		$taxes      = $args['taxes'];
231
232
		// Taxes - if not an array and not set to false, calc tax based on cost and passed calc_tax variable
233
		// This saves shipping methods having to do complex tax calculations
234
		if ( ! is_array( $taxes ) && $taxes !== false && $total_cost > 0 && $this->is_taxable() ) {
235
			switch ( $args['calc_tax'] ) {
236
				case "per_item" :
237
					$taxes = $this->get_taxes_per_item( $args['cost'] );
238
				break;
239
				default :
240
					$taxes = WC_Tax::calc_shipping_tax( $total_cost, WC_Tax::get_shipping_tax_rates() );
241
				break;
242
			}
243
		}
244
245
		$this->rates[ $args['id'] ] = new WC_Shipping_Rate( $args['id'], $args['label'], $total_cost, $taxes, $this->id );
246
	}
247
248
	/**
249
	 * Calc taxes per item being shipping in costs array.
250
	 * @since 2.6.0
251
	 * @access protected
252
	 * @param  array $costs
253
	 * @return array of taxes
254
	 */
255
	protected function get_taxes_per_item( $costs ) {
256
		$taxes = array();
257
258
		// If we have an array of costs we can look up each items tax class and add tax accordingly
259
		if ( is_array( $costs ) ) {
260
261
			$cart = WC()->cart->get_cart();
262
263
			foreach ( $costs as $cost_key => $amount ) {
264
				if ( ! isset( $cart[ $cost_key ] ) ) {
265
					continue;
266
				}
267
268
				$item_taxes = WC_Tax::calc_shipping_tax( $amount, WC_Tax::get_shipping_tax_rates( $cart[ $cost_key ]['data']->get_tax_class() ) );
269
270
				// Sum the item taxes
271
				foreach ( array_keys( $taxes + $item_taxes ) as $key ) {
272
					$taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 );
273
				}
274
			}
275
276
			// Add any cost for the order - order costs are in the key 'order'
277
			if ( isset( $costs['order'] ) ) {
278
				$item_taxes = WC_Tax::calc_shipping_tax( $costs['order'], WC_Tax::get_shipping_tax_rates() );
279
280
				// Sum the item taxes
281
				foreach ( array_keys( $taxes + $item_taxes ) as $key ) {
282
					$taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 );
283
				}
284
			}
285
		}
286
287
		return $taxes;
288
	}
289
290
	/**
291
	 * is_available function.
292
	 *
293
	 * @param array $package
294
	 * @return bool
295
	 */
296
	public function is_available( $package ) {
297
		if ( ! $this->is_enabled() ) {
298
			return false;
299
		}
300
301
		// Country availability
302
		$countries = is_array( $this->countries ) ? $this->countries : array();
1 ignored issue
show
Deprecated Code introduced by
The property WC_Shipping_Method::$countries has been deprecated with message: 2.6.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
303
304
		switch ( $this->availability ) {
1 ignored issue
show
Deprecated Code introduced by
The property WC_Shipping_Method::$availability has been deprecated with message: 2.6.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
305
			case 'specific' :
306
			case 'including' :
307
				$ship_to_countries = array_intersect( $countries, array_keys( WC()->countries->get_shipping_countries() ) );
308
			break;
309
			case 'excluding' :
310
				$ship_to_countries = array_diff( array_keys( WC()->countries->get_shipping_countries() ), $countries );
311
			break;
312
			default :
313
				$ship_to_countries = array_keys( WC()->countries->get_shipping_countries() );
314
			break;
315
		}
316
317
		if ( ! in_array( $package['destination']['country'], $ship_to_countries ) ) {
318
			return false;
319
		}
320
321
		return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', true, $package );
322
	}
323
324
	/**
325
	 * get_fee function.
326
	 *
327
	 * @param mixed $fee
328
	 * @param mixed $total
329
	 * @return float
330
	 */
331
	public function get_fee( $fee, $total ) {
332
		if ( strstr( $fee, '%' ) ) {
333
			$fee = ( $total / 100 ) * str_replace( '%', '', $fee );
334
		}
335
		if ( ! empty( $this->minimum_fee ) && $this->minimum_fee > $fee ) {
336
			$fee = $this->minimum_fee;
337
		}
338
		return $fee;
339
	}
340
341
	/**
342
	 * Does this method have a settings page?
343
	 * @return bool
344
	 */
345
	public function has_settings() {
346
		return $this->instance_id ? $this->supports( 'instance-settings' ) : $this->supports( 'settings' );
347
	}
348
349
	/**
350
	 * Output the shipping settings screen.
351
	 */
352
	public function admin_options() {
353
		if ( $this->instance_id ) {
354
			echo wp_kses_post( wpautop( $this->get_method_description() ) );
355
			echo '<table class="form-table">' . $this->generate_settings_html( $this->get_instance_form_fields(), false ) . '</table>';
356
		} else {
357
			echo '<h2>' . esc_html( $this->get_method_title() ) . '</h2>';
358
			echo wp_kses_post( wpautop( $this->get_method_description() ) );
359
			echo '<table class="form-table">' . $this->generate_settings_html( $this->get_form_fields(), false ) . '</table>';
360
		}
361
	}
362
363
	/**
364
	 * get_option function.
365
	 *
366
	 * Gets and option from the settings API, using defaults if necessary to prevent undefined notices.
367
	 *
368
	 * @param  string $key
369
	 * @param  mixed  $empty_value
370
	 * @return mixed  The value specified for the option or a default value for the option.
371
	 */
372
	public function get_option( $key, $empty_value = null ) {
373
		// Instance options take priority over global options
374
		if ( in_array( $key, array_keys( $this->get_instance_form_fields() ) ) ) {
375
			return $this->get_instance_option( $key, $empty_value );
376
		}
377
378
		// Return global option
379
		return parent::get_option( $key, $empty_value );
380
	}
381
382
	/**
383
	 * get_option function.
384
	 *
385
	 * Gets and option from the settings API, using defaults if necessary to prevent undefined notices.
386
	 *
387
	 * @param  string $key
388
	 * @param  mixed  $empty_value
389
	 * @return mixed  The value specified for the option or a default value for the option.
390
	 */
391 View Code Duplication
	public function get_instance_option( $key, $empty_value = null ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
392
		if ( empty( $this->instance_settings ) ) {
393
			$this->init_instance_settings();
394
		}
395
396
		// Get option default if unset.
397
		if ( ! isset( $this->instance_settings[ $key ] ) ) {
398
			$form_fields                     = $this->get_instance_form_fields();
399
			$this->instance_settings[ $key ] = $this->get_field_default( $form_fields[ $key ] );
400
		}
401
402
		if ( ! is_null( $empty_value ) && '' === $this->instance_settings[ $key ] ) {
403
			$this->instance_settings[ $key ] = $empty_value;
404
		}
405
406
		return $this->instance_settings[ $key ];
407
	}
408
409
	/**
410
	 * Get settings fields for instances of this shipping method (within zones).
411
	 * Should be overridden by shipping methods to add options.
412
	 * @since 2.6.0
413
	 * @return array
414
	 */
415
	public function get_instance_form_fields() {
416
		return apply_filters( 'woocommerce_shipping_instance_form_fields_' . $this->id, $this->instance_form_fields );
417
	}
418
419
	/**
420
	 * Return the name of the option in the WP DB.
421
	 * @since 2.6.0
422
	 * @return string
423
	 */
424
	public function get_instance_option_key() {
425
		return $this->instance_id ? $this->plugin_id . $this->id . $this->instance_id . '_settings' : '';
426
	}
427
428
	/**
429
	 * Initialise Settings for instances.
430
	 * @since 2.6.0
431
	 */
432 View Code Duplication
	public function init_instance_settings() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
433
		$this->instance_settings = get_option( $this->get_instance_option_key(), null );
434
435
		// If there are no settings defined, use defaults.
436
		if ( ! is_array( $this->instance_settings ) ) {
437
			$form_fields             = $this->get_instance_form_fields();
438
			$this->instance_settings = array_merge( array_fill_keys( array_keys( $form_fields ), '' ), wp_list_pluck( $form_fields, 'default' ) );
439
		}
440
	}
441
442
	/**
443
	 * Processes and saves options.
444
	 * If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
445
	 * @since 2.6.0
446
	 * @return bool was anything saved?
447
	 */
448
	public function process_admin_options() {
449
		if ( $this->instance_id ) {
450
			$this->init_instance_settings();
451
452 View Code Duplication
			foreach ( $this->get_instance_form_fields() as $key => $field ) {
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...
453
				if ( ! in_array( $this->get_field_type( $field ), array( 'title' ) ) ) {
454
					try {
455
						$this->instance_settings[ $key ] = $this->get_field_value( $key, $field );
456
					} catch ( Exception $e ) {
457
						$this->add_error( $e->getMessage() );
458
					}
459
				}
460
			}
461
462
			return update_option( $this->get_instance_option_key(), apply_filters( 'woocommerce_shipping_' . $this->id . '_instance_settings_values', $this->instance_settings, $this ) );
463
		} else {
464
			return parent::process_admin_options();
465
		}
466
	}
467
}
468