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

WC_Shipping_Flat_Rate::calculate_extra_shipping()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 8.6738
cc 5
eloc 16
nc 5
nop 3
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 14 and the first side effect is on line 3.

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
if ( ! defined( 'ABSPATH' ) ) {
3
	exit;
4
}
5
6
/**
7
 * Flat Rate Shipping Method.
8
 *
9
 * @class 		WC_Shipping_Flat_Rate
10
 * @version		2.4.0
11
 * @package		WooCommerce/Classes/Shipping
12
 * @author 		WooThemes
13
 */
14
class WC_Shipping_Flat_Rate extends WC_Shipping_Method {
15
16
	/** @var string cost passed to [fee] shortcode */
17
	protected $fee_cost = '';
18
19
	/**
20
	 * Constructor.
21
	 */
22
	public function __construct( $instance_id = 0 ) {
23
		$this->id                    = 'flat_rate';
24
		$this->instance_id 			 = absint( $instance_id );
25
		$this->method_title          = __( 'Flat Rate', 'woocommerce' );
26
		$this->method_description    = __( 'Flat Rate Shipping lets you charge a fixed rate for shipping.', 'woocommerce' );
27
		$this->supports              = array(
28
			'shipping-zones',
29
			'instance-settings'
30
		);
31
		$this->init();
32
33
		add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
34
	}
35
36
	/**
37
	 * init user set variables.
38
	 */
39
	public function init() {
40
		$this->instance_form_fields = include( 'includes/settings-flat-rate.php' );
41
		$this->title                = $this->get_option( 'title' );
42
		$this->availability         = $this->get_option( 'availability' );
0 ignored issues
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...
43
		$this->countries            = $this->get_option( 'countries' );
0 ignored issues
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...
44
		$this->tax_status           = $this->get_option( 'tax_status' );
45
		$this->cost                 = $this->get_option( 'cost' );
46
		$this->type                 = $this->get_option( 'type', 'class' );
47
	}
48
49
	/**
50
	 * Evaluate a cost from a sum/string.
51
	 * @param  string $sum
52
	 * @param  array  $args
53
	 * @return string
54
	 */
55
	protected function evaluate_cost( $sum, $args = array() ) {
56
		include_once( 'includes/class-wc-eval-math.php' );
57
58
		$locale   = localeconv();
59
		$decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
60
61
		$this->fee_cost = $args['cost'];
62
63
		// Expand shortcodes
64
		add_shortcode( 'fee', array( $this, 'fee' ) );
65
66
		$sum = do_shortcode( str_replace(
67
			array(
68
				'[qty]',
69
				'[cost]'
70
			),
71
			array(
72
				$args['qty'],
73
				$args['cost']
74
			),
75
			$sum
76
		) );
77
78
		remove_shortcode( 'fee', array( $this, 'fee' ) );
79
80
		// Remove whitespace from string
81
		$sum = preg_replace( '/\s+/', '', $sum );
82
83
		// Remove locale from string
84
		$sum = str_replace( $decimals, '.', $sum );
85
86
		// Trim invalid start/end characters
87
		$sum = rtrim( ltrim( $sum, "\t\n\r\0\x0B+*/" ), "\t\n\r\0\x0B+-*/" );
88
89
		// Do the math
90
		return $sum ? WC_Eval_Math::evaluate( $sum ) : 0;
91
	}
92
93
	/**
94
	 * Work out fee (shortcode).
95
	 * @param  array $atts
96
	 * @return string
97
	 */
98
	public function fee( $atts ) {
99
		$atts = shortcode_atts( array(
100
			'percent' => '',
101
			'min_fee' => ''
102
		), $atts );
103
104
		$calculated_fee = 0;
105
106
		if ( $atts['percent'] ) {
107
			$calculated_fee = $this->fee_cost * ( floatval( $atts['percent'] ) / 100 );
108
		}
109
110
		if ( $atts['min_fee'] && $calculated_fee < $atts['min_fee'] ) {
111
			$calculated_fee = $atts['min_fee'];
112
		}
113
114
		return $calculated_fee;
115
	}
116
117
	/**
118
	 * calculate_shipping function.
119
	 *
120
	 * @param array $package (default: array())
121
	 */
122
	public function calculate_shipping( $package = array() ) {
123
		$rate = array(
124
			'id'    => $this->id,
125
			'label' => $this->title,
126
			'cost'  => 0,
127
		);
128
129
		// Calculate the costs
130
		$has_costs = false; // True when a cost is set. False if all costs are blank strings.
131
		$cost      = $this->get_option( 'cost' );
132
133
		if ( $cost !== '' ) {
134
			$has_costs    = true;
135
			$rate['cost'] = $this->evaluate_cost( $cost, array(
136
				'qty'  => $this->get_package_item_qty( $package ),
137
				'cost' => $package['contents_cost']
138
			) );
139
		}
140
141
		// Add shipping class costs
142
		$found_shipping_classes = $this->find_shipping_classes( $package );
143
		$highest_class_cost     = 0;
144
145
		foreach ( $found_shipping_classes as $shipping_class => $products ) {
146
			// Also handles BW compatibility when slugs were used instead of ids
147
			$shipping_class_term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
148
			$class_cost_string   = $shipping_class_term && $shipping_class_term->term_id ? $this->get_option( 'class_cost_' . $shipping_class_term->term_id, $this->get_option( 'class_cost_' . $shipping_class, '' ) ) : $this->get_option( 'no_class_cost', '' );
149
150
			if ( $class_cost_string === '' ) {
151
				continue;
152
			}
153
154
			$has_costs  = true;
155
			$class_cost = $this->evaluate_cost( $class_cost_string, array(
156
				'qty'  => array_sum( wp_list_pluck( $products, 'quantity' ) ),
157
				'cost' => array_sum( wp_list_pluck( $products, 'line_total' ) )
158
			) );
159
160
			if ( $this->type === 'class' ) {
161
				$rate['cost'] += $class_cost;
162
			} else {
163
				$highest_class_cost = $class_cost > $highest_class_cost ? $class_cost : $highest_class_cost;
164
			}
165
		}
166
167
		if ( $this->type === 'order' && $highest_class_cost ) {
168
			$rate['cost'] += $highest_class_cost;
169
		}
170
171
		// Add the rate
172
		if ( $has_costs ) {
173
			$this->add_rate( $rate );
174
		}
175
176
		/**
177
		 * Developers can add additional flat rates based on this one via this action since @version 2.4.
178
		 *
179
		 * Previously there were (overly complex) options to add additional rates however this was not user.
180
		 * friendly and goes against what Flat Rate Shipping was originally intended for.
181
		 *
182
		 * This example shows how you can add an extra rate based on this flat rate via custom function:
183
		 *
184
		 * 		add_action( 'woocommerce_flat_rate_shipping_add_rate', 'add_another_custom_flat_rate', 10, 2 );
185
		 *
186
		 * 		function add_another_custom_flat_rate( $method, $rate ) {
187
		 * 			$new_rate          = $rate;
188
		 * 			$new_rate['id']    .= ':' . 'custom_rate_name'; // Append a custom ID.
189
		 * 			$new_rate['label'] = 'Rushed Shipping'; // Rename to 'Rushed Shipping'.
190
		 * 			$new_rate['cost']  += 2; // Add $2 to the cost.
191
		 *
192
		 * 			// Add it to WC.
193
		 * 			$method->add_rate( $new_rate );
194
		 * 		}.
195
		 */
196
		do_action( 'woocommerce_' . $this->id . '_shipping_add_rate', $this, $rate, $package );
197
	}
198
199
	/**
200
	 * Get items in package.
201
	 * @param  array $package
202
	 * @return int
203
	 */
204
	public function get_package_item_qty( $package ) {
205
		$total_quantity = 0;
206 View Code Duplication
		foreach ( $package['contents'] as $item_id => $values ) {
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...
207
			if ( $values['quantity'] > 0 && $values['data']->needs_shipping() ) {
208
				$total_quantity += $values['quantity'];
209
			}
210
		}
211
		return $total_quantity;
212
	}
213
214
	/**
215
	 * Finds and returns shipping classes and the products with said class.
216
	 * @param mixed $package
217
	 * @return array
218
	 */
219
	public function find_shipping_classes( $package ) {
220
		$found_shipping_classes = array();
221
222
		foreach ( $package['contents'] as $item_id => $values ) {
223
			if ( $values['data']->needs_shipping() ) {
224
				$found_class = $values['data']->get_shipping_class();
225
226
				if ( ! isset( $found_shipping_classes[ $found_class ] ) ) {
227
					$found_shipping_classes[ $found_class ] = array();
228
				}
229
230
				$found_shipping_classes[ $found_class ][ $item_id ] = $values;
231
			}
232
		}
233
234
		return $found_shipping_classes;
235
	}
236
}
237