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

WC_Shipping_Method::get_instance_option()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 17
Code Lines 9

Duplication

Lines 17
Ratio 100 %
Metric Value
dl 17
loc 17
rs 8.8571
cc 5
eloc 9
nc 8
nop 2
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 settings.
108
	 * @var array
109
	 */
110
	public $instance_settings  = array();
111
112
	/**
113
	 * Constructor.
114
	 * @param int $instance_id
115
	 */
116
	public function __construct( $instance_id = 0 ) {
117
		$this->instance_id = absint( $instance_id );
118
	}
119
120
	/**
121
	 * Check if a shipping method supports a given feature.
122
	 *
123
	 * Methods should override this to declare support (or lack of support) for a feature.
124
	 *
125
	 * @param $feature string The name of a feature to test support for.
126
	 * @return bool True if the shipping method supports the feature, false otherwise.
127
	 */
128
	public function supports( $feature ) {
129
		return apply_filters( 'woocommerce_shipping_method_supports', in_array( $feature, $this->supports ), $feature, $this );
130
	}
131
132
	/**
133
	 * Called to calculate shipping rates for this method. Rates can be added using the add_rate() method.
134
	 */
135
	public function calculate_shipping() {}
136
137
	/**
138
	 * Whether or not we need to calculate tax on top of the shipping rate.
139
	 * @return boolean
140
	 */
141
	public function is_taxable() {
142
		return wc_tax_enabled() && 'taxable' === $this->tax_status && ! WC()->customer->is_vat_exempt();
143
	}
144
145
	/**
146
	 * Whether or not this method is enabled in settings.
147
	 * @since 2.6.0
148
	 * @return boolean
149
	 */
150
	public function is_enabled() {
151
		return 'yes' === $this->enabled;
152
	}
153
154
	/**
155
	 * Return the shipping method instance ID.
156
	 * @since 2.6.0
157
	 * @return int
158
	 */
159
	public function get_instance_id() {
160
		return $this->instance_id;
161
	}
162
163
	/**
164
	 * Return the shipping method title.
165
	 * @since 2.6.0
166
	 * @return string
167
	 */
168
	public function get_method_title() {
169
		return apply_filters( 'woocommerce_shipping_method_title', $this->method_title, $this );
170
	}
171
172
	/**
173
	 * Return the shipping method description.
174
	 * @since 2.6.0
175
	 * @return string
176
	 */
177
	public function get_method_description() {
178
		return apply_filters( 'woocommerce_shipping_method_description', $this->method_description, $this );
179
	}
180
181
	/**
182
	 * Return the shipping title which is user set.
183
	 *
184
	 * @return string
185
	 */
186
	public function get_title() {
187
		return apply_filters( 'woocommerce_shipping_method_title', $this->title, $this->id );
188
	}
189
190
	/**
191
	 * Return calculated rates for a package.
192
	 * @since 2.6.0
193
	 * @param object $package
194
	 * @return array
195
	 */
196
	public function get_rates_for_package( $package ) {
197
		$this->rates = array();
198
		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...
199
			$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...
200
		}
201
		return $this->rates;
202
	}
203
204
	/**
205
	 * Add a shipping rate. If taxes are not set they will be calculated based on cost.
206
	 * @param array $args (default: array())
207
	 */
208
	public function add_rate( $args = array() ) {
209
		$args = wp_parse_args( $args, array(
210
			'id'        => '',          // ID for the rate
211
			'label'     => '',          // Label for the rate
212
			'cost'      => '0',         // Amount or array of costs (per item shipping)
213
			'taxes'     => '',          // Pass taxes, nothing to have it calculated for you, or 'false' to calc no tax
214
			'calc_tax'  => 'per_order'  // Calc tax per_order or per_item. Per item needs an array of costs
215
		) );
216
217
		// ID and label are required
218
		if ( ! $args['id'] || ! $args['label'] ) {
219
			return;
220
		}
221
222
		// Handle cost
223
		$total_cost = is_array( $args['cost'] ) ? array_sum( $args['cost'] ) : $args['cost'];
224
		$taxes      = $args['taxes'];
225
226
		// Taxes - if not an array and not set to false, calc tax based on cost and passed calc_tax variable
227
		// This saves shipping methods having to do complex tax calculations
228
		if ( ! is_array( $taxes ) && $taxes !== false && $total_cost > 0 && $this->is_taxable() ) {
229
			switch ( $args['calc_tax'] ) {
230
				case "per_item" :
231
					$taxes = $this->get_taxes_per_item( $args['cost'] );
232
				break;
233
				default :
234
					$taxes = WC_Tax::calc_shipping_tax( $total_cost, WC_Tax::get_shipping_tax_rates() );
235
				break;
236
			}
237
		}
238
239
		$this->rates[ $args['id'] ] = new WC_Shipping_Rate( $args['id'], $args['label'], $total_cost, $taxes, $this->id );
240
	}
241
242
	/**
243
	 * Calc taxes per item being shipping in costs array.
244
	 * @since 2.6.0
245
	 * @access protected
246
	 * @param  array $costs
247
	 * @return array of taxes
248
	 */
249
	protected function get_taxes_per_item( $costs ) {
250
		$taxes = array();
251
252
		// If we have an array of costs we can look up each items tax class and add tax accordingly
253
		if ( is_array( $costs ) ) {
254
255
			$cart = WC()->cart->get_cart();
256
257
			foreach ( $costs as $cost_key => $amount ) {
258
				if ( ! isset( $cart[ $cost_key ] ) ) {
259
					continue;
260
				}
261
262
				$item_taxes = WC_Tax::calc_shipping_tax( $amount, WC_Tax::get_shipping_tax_rates( $cart[ $cost_key ]['data']->get_tax_class() ) );
263
264
				// Sum the item taxes
265
				foreach ( array_keys( $taxes + $item_taxes ) as $key ) {
266
					$taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 );
267
				}
268
			}
269
270
			// Add any cost for the order - order costs are in the key 'order'
271
			if ( isset( $costs['order'] ) ) {
272
				$item_taxes = WC_Tax::calc_shipping_tax( $costs['order'], WC_Tax::get_shipping_tax_rates() );
273
274
				// Sum the item taxes
275
				foreach ( array_keys( $taxes + $item_taxes ) as $key ) {
276
					$taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 );
277
				}
278
			}
279
		}
280
281
		return $taxes;
282
	}
283
284
	/**
285
	 * is_available function.
286
	 *
287
	 * @param array $package
288
	 * @return bool
289
	 */
290
	public function is_available( $package ) {
291
		if ( ! $this->is_enabled() ) {
292
			return false;
293
		}
294
295
		// Country availability
296
		$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...
297
298
		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...
299
			case 'specific' :
300
			case 'including' :
301
				$ship_to_countries = array_intersect( $countries, array_keys( WC()->countries->get_shipping_countries() ) );
302
			break;
303
			case 'excluding' :
304
				$ship_to_countries = array_diff( array_keys( WC()->countries->get_shipping_countries() ), $countries );
305
			break;
306
			default :
307
				$ship_to_countries = array_keys( WC()->countries->get_shipping_countries() );
308
			break;
309
		}
310
311
		if ( ! in_array( $package['destination']['country'], $ship_to_countries ) ) {
312
			return false;
313
		}
314
315
		return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', true, $package );
316
	}
317
318
	/**
319
	 * get_fee function.
320
	 *
321
	 * @param mixed $fee
322
	 * @param mixed $total
323
	 * @return float
324
	 */
325
	public function get_fee( $fee, $total ) {
326
		if ( strstr( $fee, '%' ) ) {
327
			$fee = ( $total / 100 ) * str_replace( '%', '', $fee );
328
		}
329
		if ( ! empty( $this->minimum_fee ) && $this->minimum_fee > $fee ) {
330
			$fee = $this->minimum_fee;
331
		}
332
		return $fee;
333
	}
334
335
	/**
336
	 * Does this method have a settings page?
337
	 * @return bool
338
	 */
339
	public function has_settings() {
340
		return $this->instance_id ? $this->supports( 'instance-settings' ) : $this->supports( 'settings' );
341
	}
342
343
	/**
344
	 * Output the shipping settings screen.
345
	 */
346
	public function admin_options() {
347
		if ( $this->instance_id ) {
348
			echo wp_kses_post( wpautop( $this->get_method_description() ) );
349
			echo '<table class="form-table">' . $this->generate_settings_html( $this->get_instance_form_fields(), false ) . '</table>';
350
		} else {
351
			echo '<h2>' . esc_html( $this->get_method_title() ) . '</h2>';
352
			echo wp_kses_post( wpautop( $this->get_method_description() ) );
353
			echo '<table class="form-table">' . $this->generate_settings_html( $this->get_form_fields(), false ) . '</table>';
354
		}
355
	}
356
357
	/**
358
	 * get_option function.
359
	 *
360
	 * Gets and option from the settings API, using defaults if necessary to prevent undefined notices.
361
	 *
362
	 * @param  string $key
363
	 * @param  mixed  $empty_value
364
	 * @return mixed  The value specified for the option or a default value for the option.
365
	 */
366
	public function get_option( $key, $empty_value = null ) {
367
		// Instance options take priority over global options
368
		if ( in_array( $key, array_keys( $this->get_instance_form_fields() ) ) ) {
369
			return $this->get_instance_option( $key, $empty_value );
370
		}
371
372
		// Return global option
373
		return parent::get_option( $key, $empty_value );
374
	}
375
376
	/**
377
	 * get_option function.
378
	 *
379
	 * Gets and option from the settings API, using defaults if necessary to prevent undefined notices.
380
	 *
381
	 * @param  string $key
382
	 * @param  mixed  $empty_value
383
	 * @return mixed  The value specified for the option or a default value for the option.
384
	 */
385 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...
386
		if ( empty( $this->instance_settings ) ) {
387
			$this->init_instance_settings();
388
		}
389
390
		// Get option default if unset.
391
		if ( ! isset( $this->instance_settings[ $key ] ) ) {
392
			$form_fields                     = $this->get_instance_form_fields();
393
			$this->instance_settings[ $key ] = $this->get_field_default( $form_fields[ $key ] );
394
		}
395
396
		if ( ! is_null( $empty_value ) && '' === $this->instance_settings[ $key ] ) {
397
			$this->instance_settings[ $key ] = $empty_value;
398
		}
399
400
		return $this->instance_settings[ $key ];
401
	}
402
403
	/**
404
	 * Get settings fields for instances of this shipping method (within zones).
405
	 * Should be overridden by shipping methods to add options.
406
	 * @since 2.6.0
407
	 * @return array
408
	 */
409
	public function get_instance_form_fields() {
410
		return array();
411
	}
412
413
	/**
414
	 * Return the name of the option in the WP DB.
415
	 * @since 2.6.0
416
	 * @return string
417
	 */
418
	public function get_instance_option_key() {
419
		return $this->instance_id ? $this->plugin_id . $this->id . $this->instance_id . '_settings' : '';
420
	}
421
422
	/**
423
	 * Initialise Settings for instances.
424
	 * @since 2.6.0
425
	 */
426 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...
427
		$this->instance_settings = get_option( $this->get_instance_option_key(), null );
428
429
		// If there are no settings defined, use defaults.
430
		if ( ! is_array( $this->instance_settings ) ) {
431
			$form_fields             = $this->get_instance_form_fields();
432
			$this->instance_settings = array_merge( array_fill_keys( array_keys( $form_fields ), '' ), wp_list_pluck( $form_fields, 'default' ) );
433
		}
434
	}
435
436
	/**
437
	 * Processes and saves options.
438
	 * If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
439
	 * @since 2.6.0
440
	 * @return bool was anything saved?
441
	 */
442
	public function process_admin_options() {
443
		if ( $this->instance_id ) {
444
			$this->init_instance_settings();
445
446 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...
447
				if ( ! in_array( $this->get_field_type( $field ), array( 'title' ) ) ) {
448
					try {
449
						$this->instance_settings[ $key ] = $this->get_field_value( $key, $field );
450
					} catch ( Exception $e ) {
451
						$this->add_error( $e->getMessage() );
452
					}
453
				}
454
			}
455
456
			return update_option( $this->get_instance_option_key(), apply_filters( 'woocommerce_shipping_' . $this->id . '_instance_settings_values', $this->instance_settings, $this ) );
457
		} else {
458
			return parent::process_admin_options();
459
		}
460
	}
461
}
462