Completed
Pull Request — master (#9826)
by Mike
15:37
created

WC_Shipping_Flat_Rate   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 224
Duplicated Lines 48.66 %

Coupling/Cohesion

Components 1
Dependencies 2
Metric Value
wmc 27
lcom 1
cbo 2
dl 109
loc 224
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A init() 0 10 1
B evaluate_cost() 37 37 2
A fee() 18 18 4
C calculate_shipping() 28 76 11
A get_package_item_qty() 9 9 4
A find_shipping_classes() 17 17 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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