Completed
Pull Request — master (#9826)
by Mike
07:48
created

WC_Shipping_Flat_Rate   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 225
Duplicated Lines 32 %

Coupling/Cohesion

Components 1
Dependencies 2
Metric Value
wmc 27
lcom 1
cbo 2
dl 72
loc 225
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A init() 0 10 1
B evaluate_cost() 0 38 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...
Documentation Bug introduced by
It seems like $this->get_option('countries') of type * is incompatible with the declared type array of property $countries.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

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