Completed
Push — master ( 77da7c...c757fd )
by Mike
09:37
created

WC_Shipping_Method::get_admin_options_html()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 0
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
	 * - instance-settings-modal Allows the instance settings to be loaded within a modal in the zones UI.
26
	 * @var array
27
	 */
28
	public $supports = array( 'settings' );
29
30
	/**
31
	 * Unique ID for the shipping method - must be set.
32
	 * @var string
33
	 */
34
	public $id = '';
35
36
	/**
37
	 * Method title.
38
	 * @var string
39
	 */
40
	public $method_title = '';
41
42
	/**
43
	 * Method description.
44
	 * @var string
45
	 */
46
	public $method_description = '';
47
48
	/**
49
	 * yes or no based on whether the method is enabled.
50
	 * @var string
51
	 */
52
	public $enabled = 'yes';
53
54
	/**
55
	 * Shipping method title for the frontend.
56
	 * @var string
57
	 */
58
	public $title;
59
60
	/**
61
	 * This is an array of rates - methods must populate this array to register shipping costs.
62
	 * @var array
63
	 */
64
	public $rates = array();
65
66
	/**
67
	 * If 'taxable' tax will be charged for this method (if applicable).
68
	 * @var string
69
	 */
70
	public $tax_status = 'taxable';
71
72
	/**
73
	 * Fee for the method (if applicable).
74
	 * @var string
75
	 */
76
	public $fee = null;
77
78
	/**
79
	 * Minimum fee for the method (if applicable).
80
	 * @var string
81
	 */
82
	public $minimum_fee = null;
83
84
	/**
85
	 * Instance ID if used.
86
	 * @var int
87
	 */
88
	public $instance_id = 0;
89
90
	/**
91
	 * Instance form fields.
92
	 * @var array
93
	 */
94
	public $instance_form_fields = array();
95
96
	/**
97
	 * Instance settings.
98
	 * @var array
99
	 */
100
	public $instance_settings = array();
101
102
	/**
103
	 * Availability - legacy. Used for method Availability.
104
	 * No longer useful for instance based shipping methods.
105
	 * @deprecated 2.6.0
106
	 * @var string
107
	 */
108
	public $availability;
109
110
	/**
111
	 * Availability countries - legacy. Used for method Availability.
112
	 * No longer useful for instance based shipping methods.
113
	 * @deprecated 2.6.0
114
	 * @var array
115
	 */
116
	public $countries = 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( $package = array() ) {}
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
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...
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
	 * @param array $package option to store information about the package in meta.
214
	 */
215
	public function add_rate( $args = array(), $package = false ) {
216
		$args = wp_parse_args( $args, array(
217
			'id'        => '', // ID for the rate
218
			'label'     => '', // Label for the rate
219
			'cost'      => '0', // Amount or array of costs (per item shipping)
220
			'taxes'     => '', // Pass taxes, or leave empty to have it calculated for you, or 'false' to disable calculations
221
			'calc_tax'  => 'per_order', // Calc tax per_order or per_item. Per item needs an array of costs
222
			'meta_data' => array() // Array of misc meta data to store along with this rate - key value pairs.
223
		) );
224
225
		// ID and label are required
226
		if ( ! $args['id'] || ! $args['label'] ) {
227
			return;
228
		}
229
230
		// Total up the cost
231
		$total_cost = is_array( $args['cost'] ) ? array_sum( $args['cost'] ) : $args['cost'];
232
		$taxes      = $args['taxes'];
233
234
		// Taxes - if not an array and not set to false, calc tax based on cost and passed calc_tax variable. This saves shipping methods having to do complex tax calculations.
235
		if ( ! is_array( $taxes ) && $taxes !== false && $total_cost > 0 && $this->is_taxable() ) {
236
			$taxes = 'per_item' === $args['calc_tax'] ? $this->get_taxes_per_item( $args['cost'] ) : WC_Tax::calc_shipping_tax( $total_cost, WC_Tax::get_shipping_tax_rates() );
237
		}
238
239
		// Round the total cost after taxes have been calculated.
240
		$total_cost = wc_format_decimal( $total_cost, wc_get_price_decimals() );
241
242
		// Create rate object
243
		$rate = new WC_Shipping_Rate( $args['id'], $args['label'], $total_cost, $taxes, $this->id );
0 ignored issues
show
Documentation introduced by
$total_cost is of type string|array, but the function expects a integer.

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...
244
245
		if ( ! empty( $args['meta_data'] ) ) {
246
			foreach ( $args['meta_data'] as $key => $value ) {
247
				$rate->add_meta_data( $key, $value );
248
			}
249
		}
250
251
		// Store package data
252
		if ( $package ) {
253
			$items_in_package = array();
254
			foreach ( $package['contents'] as $item ) {
255
				$product = $item['data'];
256
				$items_in_package[] = $product->get_title() . ' &times; ' . $item['quantity'];
257
			}
258
			$rate->add_meta_data( __( 'Items', 'woocommerce' ), implode( ', ', $items_in_package ) );
259
		}
260
261
		$this->rates[ $args['id'] ] = $rate;
262
	}
263
264
	/**
265
	 * Calc taxes per item being shipping in costs array.
266
	 * @since 2.6.0
267
	 * @access protected
268
	 * @param  array $costs
269
	 * @return array of taxes
270
	 */
271
	protected function get_taxes_per_item( $costs ) {
272
		$taxes = array();
273
274
		// If we have an array of costs we can look up each items tax class and add tax accordingly
275
		if ( is_array( $costs ) ) {
276
277
			$cart = WC()->cart->get_cart();
278
279
			foreach ( $costs as $cost_key => $amount ) {
280
				if ( ! isset( $cart[ $cost_key ] ) ) {
281
					continue;
282
				}
283
284
				$item_taxes = WC_Tax::calc_shipping_tax( $amount, WC_Tax::get_shipping_tax_rates( $cart[ $cost_key ]['data']->get_tax_class() ) );
285
286
				// Sum the item taxes
287 View Code Duplication
				foreach ( array_keys( $taxes + $item_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...
288
					$taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 );
289
				}
290
			}
291
292
			// Add any cost for the order - order costs are in the key 'order'
293
			if ( isset( $costs['order'] ) ) {
294
				$item_taxes = WC_Tax::calc_shipping_tax( $costs['order'], WC_Tax::get_shipping_tax_rates() );
295
296
				// Sum the item taxes
297 View Code Duplication
				foreach ( array_keys( $taxes + $item_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...
298
					$taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 );
299
				}
300
			}
301
		}
302
303
		return $taxes;
304
	}
305
306
	/**
307
	 * Is this method available?
308
	 * @param array $package
309
	 * @return bool
310
	 */
311
	public function is_available( $package ) {
312
		$available = $this->is_enabled();
313
314
		// Country availability (legacy, for non-zone based methods)
315
		if ( ! $this->instance_id ) {
316
			$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...
317
318
			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...
319
				case 'specific' :
320 View Code Duplication
				case 'including' :
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...
321
					$available = in_array( $package['destination']['country'], array_intersect( $countries, array_keys( WC()->countries->get_shipping_countries() ) ) );
322
				break;
323 View Code Duplication
				case 'excluding' :
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...
324
					$available = in_array( $package['destination']['country'], array_diff( array_keys( WC()->countries->get_shipping_countries() ), $countries ) );
325
				break;
326 View Code Duplication
				default :
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...
327
					$available = in_array( $package['destination']['country'], array_keys( WC()->countries->get_shipping_countries() ) );
328
				break;
329
			}
330
		}
331
332
		return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', $available, $package );
333
	}
334
335
	/**
336
	 * Get fee to add to shipping cost.
337
	 * @param string|float $fee
338
	 * @param float $total
339
	 * @return float
340
	 */
341
	public function get_fee( $fee, $total ) {
342
		if ( strstr( $fee, '%' ) ) {
343
			$fee = ( $total / 100 ) * str_replace( '%', '', $fee );
344
		}
345
		if ( ! empty( $this->minimum_fee ) && $this->minimum_fee > $fee ) {
346
			$fee = $this->minimum_fee;
347
		}
348
		return $fee;
349
	}
350
351
	/**
352
	 * Does this method have a settings page?
353
	 * @return bool
354
	 */
355
	public function has_settings() {
356
		return $this->instance_id ? $this->supports( 'instance-settings' ) : $this->supports( 'settings' );
357
	}
358
359
	/**
360
	 * Return admin options as a html string.
361
	 * @return string
362
	 */
363
	public function get_admin_options_html() {
364
		if ( $this->instance_id ) {
365
			$settings_html = $this->generate_settings_html( $this->get_instance_form_fields(), false );
366
		} else {
367
			$settings_html = $this->generate_settings_html( $this->get_form_fields(), false );
368
		}
369
370
		return '<table class="form-table">' . $settings_html . '</table>';
371
	}
372
373
	/**
374
	 * Output the shipping settings screen.
375
	 */
376
	public function admin_options() {
377
		if ( ! $this->instance_id ) {
378
			echo '<h2>' . esc_html( $this->get_method_title() ) . '</h2>';
379
		}
380
		echo wp_kses_post( wpautop( $this->get_method_description() ) );
381
		echo $this->get_admin_options_html();
382
	}
383
384
	/**
385
	 * get_option function.
386
	 *
387
	 * Gets and option from the settings API, using defaults if necessary to prevent undefined notices.
388
	 *
389
	 * @param  string $key
390
	 * @param  mixed  $empty_value
391
	 * @return mixed  The value specified for the option or a default value for the option.
392
	 */
393
	public function get_option( $key, $empty_value = null ) {
394
		// Instance options take priority over global options
395
		if ( array_key_exists( $key, $this->get_instance_form_fields() ) ) {
396
			return $this->get_instance_option( $key, $empty_value );
397
		}
398
399
		// Return global option
400
		return parent::get_option( $key, $empty_value );
401
	}
402
403
	/**
404
	 * Gets an option from the settings API, using defaults if necessary to prevent undefined notices.
405
	 *
406
	 * @param  string $key
407
	 * @param  mixed  $empty_value
408
	 * @return mixed  The value specified for the option or a default value for the option.
409
	 */
410 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...
411
		if ( empty( $this->instance_settings ) ) {
412
			$this->init_instance_settings();
413
		}
414
415
		// Get option default if unset.
416
		if ( ! isset( $this->instance_settings[ $key ] ) ) {
417
			$form_fields                     = $this->get_instance_form_fields();
418
			$this->instance_settings[ $key ] = $this->get_field_default( $form_fields[ $key ] );
419
		}
420
421
		if ( ! is_null( $empty_value ) && '' === $this->instance_settings[ $key ] ) {
422
			$this->instance_settings[ $key ] = $empty_value;
423
		}
424
425
		return $this->instance_settings[ $key ];
426
	}
427
428
	/**
429
	 * Get settings fields for instances of this shipping method (within zones).
430
	 * Should be overridden by shipping methods to add options.
431
	 * @since 2.6.0
432
	 * @return array
433
	 */
434
	public function get_instance_form_fields() {
435
		return apply_filters( 'woocommerce_shipping_instance_form_fields_' . $this->id, $this->instance_form_fields );
436
	}
437
438
	/**
439
	 * Return the name of the option in the WP DB.
440
	 * @since 2.6.0
441
	 * @return string
442
	 */
443
	public function get_instance_option_key() {
444
		return $this->instance_id ? $this->plugin_id . $this->id . '_' . $this->instance_id . '_settings' : '';
445
	}
446
447
	/**
448
	 * Initialise Settings for instances.
449
	 * @since 2.6.0
450
	 */
451 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...
452
		$this->instance_settings = get_option( $this->get_instance_option_key(), null );
453
454
		// If there are no settings defined, use defaults.
455
		if ( ! is_array( $this->instance_settings ) ) {
456
			$form_fields             = $this->get_instance_form_fields();
457
			$this->instance_settings = array_merge( array_fill_keys( array_keys( $form_fields ), '' ), wp_list_pluck( $form_fields, 'default' ) );
458
		}
459
	}
460
461
	/**
462
	 * Processes and saves options.
463
	 * If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
464
	 * @since 2.6.0
465
	 * @param  array $post_data Defaults to $_POST but can be passed in.
466
	 * @return bool was anything saved?
467
	 */
468
	public function process_admin_options( $post_data = array() ) {
469
		if ( $this->instance_id ) {
470
			$this->init_instance_settings();
471
472
			if ( empty( $post_data ) ) {
473
				$post_data = $_POST;
474
			}
475
476 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...
477
				if ( 'title' !== $this->get_field_type( $field ) ) {
478
					try {
479
						$this->instance_settings[ $key ] = $this->get_field_value( $key, $field, $post_data );
480
					} catch ( Exception $e ) {
481
						$this->add_error( $e->getMessage() );
482
					}
483
				}
484
			}
485
486
			return update_option( $this->get_instance_option_key(), apply_filters( 'woocommerce_shipping_' . $this->id . '_instance_settings_values', $this->instance_settings, $this ) );
487
		} else {
488
			return parent::process_admin_options();
489
		}
490
	}
491
}
492