wps_shipping::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php if ( !defined( 'ABSPATH' ) ) exit;
2
class wps_shipping {
3
	function __construct() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
4
5
	}
6
7
	/**
8
	 * Convert fees (string format) to fees in array format
9
	 * @param $fees_string : fees string type by the user
10
	 * @return $data : fees in array format
0 ignored issues
show
Documentation introduced by
The doc-type $data could not be parsed: Unknown type name "$data" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
11
	 */
12
	function shipping_fees_string_2_array($fees_string) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
13
		$data = array();
14
		if(!empty($fees_string) && !is_array($fees_string) ) {
15
			if(preg_match_all('#{[^{]+}#', $fees_string, $cont)){
16
				foreach($cont[0] as $c) {
17
					preg_match_all('#([a-z]+) ?: ?"(.+)"#', $c, $atts);
18
					$temp_data = array();
19
					$country_code = '';
20
					foreach($atts[1] as $key => $value) {
21
						$temp_data[$value] =  $atts[2][$key];
22
						if($value=='destination') {
23
							$country_code = $atts[2][$key];
24
						}
25
						elseif($value=='fees') {
26
							$fees_data = array();
27
							$fees = explode(',', $atts[2][$key]);
28
							foreach($fees as $fee){
29
								$fee_element = explode(':', $fee);
30
								$fees_data[trim($fee_element[0])] =  trim($fee_element[1]);
31
							}
32
							$number = count($fees_data);
33
34
							$fees_data_1 = array();
35
							preg_match_all('#([0-9]+\.?[0-9]?+) ?: ?([0-9]+\.?[0-9]?+)#', $atts[2][$key], $fees);
36
							foreach($fees[1] as $_key => $_value) {
37
								$fees_data_1[$_value] =  $fees[2][$_key];
38
							}
39
							$number_1 = count($fees_data_1);
40
							if ($number == $number_1) {
41
								$temp_data[$value] =  $fees_data;
42
							}
43
							else {
44
								$temp_data[$value] =  $fees_data_1;
45
							}
46
						}
47
					}
48
					if(!empty($country_code)) {
49
						$data[$country_code] = $temp_data;
50
					}
51
				}
52
			}
53
			return $data;
54
		}
55
		return array();
56
	}
57
58
	/**
59
	 * Convert fees (array format) to fees in string format
60
	 * @param $fees_array : fees in array format
61
	 * @return $string : fees in string format
0 ignored issues
show
Documentation introduced by
The doc-type $string could not be parsed: Unknown type name "$string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
62
	 */
63
	function shipping_fees_array_2_string($fees_array) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
64
		$string = '';
65
		if(!empty($fees_array)) {
66
			foreach($fees_array as $d) {
67
				$string .= '{'."\n";
68
				foreach($d as $att => $value) {
69
					$val = '';
70
					if($att=='fees') {
71
						foreach($value as $_k=>$_value) $val .= $_k.':'.$_value.', ';
72
						$val = substr($val,0,-2);
73
					} else $val = $value;
74
					$string .= $att.': "'.$val.'",'."\n";
75
				}
76
				$string = substr($string,0,-2)."\n";
77
				$string .= '},'."\n";
78
			}
79
			$string = substr($string,0,-2);
80
			return $string;
81
		}
82
		else return false;
83
	}
84
85
	/**
86
	 * Get the shipping cost for the current cart
87
	 *
88
	 * @param integer $nb_of_items The number of items in cart
89
	 * @param float $total_cart The amount of the cart
90
	 * @param float $total_shipping_cost The amount of the shipping cost calculate from the sum of shipping cost for each product in cart
91
	 * @param float $total_weight The total weight of all product in cart
92
	 *
93
	 * @return number|string The sipping cost for the current cart
94
	 */
95
	 function get_shipping_cost( $nb_of_items, $total_cart, $total_shipping_cost, $total_weight, $selected_method = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $nb_of_items is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
96
 		global $wpdb;
97
98
 		$shipping_cost = 0;
99
100
 		$shipping_mode_state = get_option( 'wpshop_shipping_address_choice' );
101
 		if ( ! empty( $shipping_mode_state ) && isset( $shipping_mode_state['activate'] ) && ( 'on' === $shipping_mode_state['activate'] ) ) {
102
 			$shipping_mode_option = get_option( 'wps_shipping_mode' );
103
 			if( ( !empty($selected_method) || isset( $_SESSION['shipping_address'] ) && empty( $_SESSION['shipping_method'] ) ) ) {
104
 				if( !empty($selected_method) ) {
105
 					$chosen_shipping_mode = $selected_method;
106
 				} else {
107
 					$ship_mod = new wps_shipping_mode_ctr();
108
 					$shipping_modes = $ship_mod->get_shipping_mode_for_address( $_SESSION['shipping_address'] );
109
 					if( !empty( $shipping_modes ) ) {
110
 						$shipping_modes = $shipping_modes['modes'];
111
 						foreach( $shipping_modes as $key => $shipping_mode ) {
112
 							$chosen_shipping_mode = $key;
113
 							break;
114
 						}
115
 					} else {
116
 						$chosen_shipping_mode = 'default_choice';
117
 					}
118
 				}
119
 			}
120
 			else {
121
 				if( !empty( $_SESSION['shipping_method'] ) ) {
122
 					$chosen_shipping_mode = wpshop_tools::varSanitizer( $_SESSION['shipping_method'] );
123
 				} else {
124
 					$chosen_shipping_mode = 'default_choice';
125
 				}
126
 			}
127
128
 			$default_weight_unity = get_option( 'wpshop_shop_default_weight_unity' );
129
 			if ( !empty($default_weight_unity) ) {
130
 				$query = $wpdb->prepare('SELECT unit FROM ' .WPSHOP_DBT_ATTRIBUTE_UNIT. ' WHERE id = %d', $default_weight_unity);
131
 				$weight_unity = $wpdb->get_var( $query );
132
133
 				if ( !empty($weight_unity) && $weight_unity == 'kg' ) {
134
135
 					$total_weight = $total_weight * 1000;
136
 				}
137
 			}
138
139
 			if ( ( !empty($_SESSION['shipping_method']) && $_SESSION['shipping_method'] == 'shipping-partners' ) || !empty( $_SESSION['wps-pos-addon']) ) {
140
 				return 0;
141
 			}
142
143
 			/** Take the selected shipping mode **/
144
 			if( $chosen_shipping_mode == 'default_choice' ) {
145 View Code Duplication
 				if( !empty( $shipping_mode_option['modes'][ $shipping_mode_option['default_choice'] ]) ) {
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...
146
 					$selected_shipping_mode_config = $shipping_mode_option['modes'][ $shipping_mode_option['default_choice'] ];
147
 				} else {
148
 					$selected_shipping_mode_config = '';
149
 				}
150 View Code Duplication
 			} else {
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...
151
 				if( !empty( $shipping_mode_option['modes'][$chosen_shipping_mode]) ) {
152
 					$selected_shipping_mode_config = $shipping_mode_option['modes'][$chosen_shipping_mode];
0 ignored issues
show
Bug introduced by
The variable $chosen_shipping_mode does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
153
 				} else {
154
 					$selected_shipping_mode_config = '';
155
 				}
156
 			}
157
 			$shipping_cost = $total_shipping_cost;
158
159
 			/** Free Shipping **/
160
 			if ( ( !empty($selected_shipping_mode_config) && !empty($selected_shipping_mode_config['free_shipping']) ) || ( $selected_method == 'is_downloadable_' ) ) {
161
 				$shipping_cost = 0;
162
 			}
163
 			/** Free Shipping From **/
164
 			elseif( !empty($selected_shipping_mode_config) && !empty($selected_shipping_mode_config['free_from']) && $selected_shipping_mode_config['free_from'] >= 0 && $selected_shipping_mode_config['free_from'] <= number_format( $total_cart, 2, '.', '') ) {
165
 				$shipping_cost = 0;
166
 			}
167
 			else {
168
 				/** Check Custom Shipping Cost **/
169
170
 				if ( !empty($selected_shipping_mode_config['custom_shipping_rules']) && !empty($selected_shipping_mode_config['custom_shipping_rules']['active']) ) {
171
 					$address_infos = '';
172
 					if( !empty( $_SESSION['shipping_address'] ) ) {
173
 						$address_infos = get_post_meta($_SESSION['shipping_address'],'_wpshop_address_metadata', true);
174
 					}
175
 					$country = ( !empty($address_infos['country']) ) ? $address_infos['country'] : '';
176
 					/** Check Active Postcode option **/
177
 					if ( !empty($selected_shipping_mode_config['custom_shipping_rules']['active_cp']) ) {
178
 						$postcode = $address_infos['postcode'];
179
 						if ( array_key_exists($country.'-'.$postcode, $selected_shipping_mode_config['custom_shipping_rules']['fees']) ) {
180
 							$country = $country.'-'.$postcode;
181
 						}
182
 						elseif( array_key_exists($country.'-OTHERS', $selected_shipping_mode_config['custom_shipping_rules']['fees']) ) {
183
 							$country = $country.'-OTHERS';
184
 						}
185
 					}
186
 					$shipping_cost += $this->calculate_custom_shipping_cost($country, array('weight'=>$total_weight,'price'=> $total_cart), $selected_shipping_mode_config['custom_shipping_rules']['fees'], $chosen_shipping_mode);
0 ignored issues
show
Documentation introduced by
$selected_shipping_mode_...hipping_rules']['fees'] is of type string, 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...
187
 				}
188
189
 				/** Min- Max config **/
190
 				if ( !empty($selected_shipping_mode_config['min_max']) && !empty($selected_shipping_mode_config['min_max']['activate']) ) {
191
 					if ( !empty($selected_shipping_mode_config['min_max']['min']) && $shipping_cost < $selected_shipping_mode_config['min_max']['min'] ) {
192
 						$shipping_cost = $selected_shipping_mode_config['min_max']['min'];
193
 					}
194
 					elseif( !empty($selected_shipping_mode_config['min_max']['max']) &&$shipping_cost > $selected_shipping_mode_config['min_max']['max']) {
195
 						$shipping_cost = $selected_shipping_mode_config['min_max']['max'];
196
 					}
197
198
 				}
199
 			}
200
 		}
201
 		return $shipping_cost;
202
 	}
203
204
205
	/**
206
	 * Return s custom shipping cost for a cart
207
	 * @param string $dest Shipping area zone
208
	 * @param array $data
209
	 * @param array $fees
210
	 * @return number|boolean|Ambigous <number, unknown>
211
	 */
212
	function calculate_custom_shipping_cost($dest='', $data, $fees, $shipping_method = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
213
		$fees_table = array();
0 ignored issues
show
Unused Code introduced by
$fees_table is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
214
		$key = ''; $price = 0;
215
216
		if ( !empty($_SESSION['shipping_partner_id']) ) {
217
			return 0;
218
		}
219
220
		if($shipping_method === false) {
221
			$shipping_method = $_SESSION['shipping_method'];
222
		}
223
224
		if(!empty($fees) || !empty($dest) ) {
225
			$custom_shipping_option = get_option( 'wpshop_custom_shipping', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, 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...
226
			$shipping_modes = get_option( 'wps_shipping_mode' );
227
228
			if ( !empty($shipping_method) ) {
229
				if ( !empty($shipping_modes) && !empty($shipping_modes['modes']) && !empty($shipping_modes['modes'][ $shipping_method ]) ) {
230
					$custom_shipping_option = $shipping_modes['modes'][ $shipping_method ]['custom_shipping_rules'];
231
				}
232
			}
233
			$found_active_cp_rule = $found_active_departement_rule = false;
234
			$shipping_address_def = get_post_meta( $_SESSION['shipping_address'], '_wpshop_address_metadata', true );
235
			$postcode = '';
236
			if ( !empty($shipping_address_def) ) {
237
				$postcode = $shipping_address_def['postcode'];
238
			}
239
240
			/** Search Postcode custom fees **/
241
			if ( !empty($custom_shipping_option) && !empty($custom_shipping_option['active_cp']) ) {
242
				$key = $dest.'-'.$postcode;
243 View Code Duplication
				if ( array_key_exists($key, $fees) ) {
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...
244
					foreach ($fees[$key]['fees'] as $k => $shipping_price) {
245
						if ( $data['weight'] <= $k) {
246
							break;
247
						}
248
					}
249
					$found_active_cp_rule = true;
250
				}
251
			}
252
253
			/** Search Department custom fees **/
254
			if( !empty($custom_shipping_option) && !empty($custom_shipping_option['active_department']) && !$found_active_cp_rule ) {
255
				$department = substr( $postcode, 0,2 );
256
				$key = $dest.'-'.$department;
257
				/** Check if a rule exists **/
258 View Code Duplication
				if ( array_key_exists($key, $fees) ) {
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...
259
					foreach ($fees[$key]['fees'] as $k => $shipping_price) {
260
						if ( $data['weight'] <= $k) {
261
							break;
262
						}
263
					}
264
					$found_active_departement_rule = true;
265
				}
266
			}
267
268
			/** Search general custom fees **/
269
			if( !$found_active_cp_rule && !$found_active_departement_rule ){
270
				if ( array_key_exists($dest, $fees) ) {
271
					$key = $dest;
272
				}
273
				elseif( array_key_exists( 'OTHERS', $fees) ) {
274
					$key = 'OTHERS';
275
				}
276
				else {
277
					return false;
278
				}
279
			}
280
281
			//Search fees
282
			if ( !empty($key) ) {
283
				ksort( $fees[$key]['fees'] );
284
				foreach ($fees[$key]['fees'] as $k => $shipping_price) {
285
					if ( $data['weight'] <= $k) {
286
						$price = $shipping_price;
287
						break;
288
					}
289
					if ($shipping_price === end($fees[$key]['fees'])) {
290
						$price = $shipping_price;
291
					}
292
				}
293
			}
294
			else {
295
				return false;
296
			}
297
			return $price;
298
		}
299
		return false;
300
	}
301
302
	/**
303
	 * Return Amount of Shipping Cost for Cart items
304
	 * @param array $cart_items
305
	 * @return number
306
	 */
307
	function calcul_cart_items_shipping_cost( $cart_items ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
308
		$shipping_cost = 0;
309
		if( !empty($cart_items) ) {
310
			foreach( $cart_items as $cart_item ) {
311
				$product_data = get_post_meta( $cart_item['item_id'], '_wpshop_product_metadata', true );
312
313
				if ( !empty( $product_data ) && !empty( $product_data['cost_of_postage'] ) ) {
314
					$shipping_cost += ( $product_data['cost_of_postage'] * $cart_item['item_qty'] );
315
				}
316
			}
317
		}
318
319
		return $shipping_cost;
320
	}
321
322
	/**
323
	 * Return the cart total weight
324
	 * @param array $cart_items
325
	 * @return number
326
	 */
327
	function calcul_cart_weight( $cart_items ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
328
		$cart_weight = 0;
329
		if ( !empty( $cart_items) ) {
330
			foreach( $cart_items as $id_item => $cart_item ) {
331
				$id_item = wpshop_products::get_id_variation($id_item);
332
				if ( get_post_type($id_item) == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION ) {
333
					$product_data = get_post_meta( $id_item, '_wpshop_product_metadata', true );
334
					if ( !empty($product_data) && !empty($product_data['product_weight']) ) {
335
						$cart_weight += ( $product_data['product_weight'] * $cart_item['item_qty'] );
336
					}
337 View Code Duplication
					else {
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...
338
						$parent_def = wpshop_products::get_parent_variation( $id_item );
339
						if ( !empty($parent_def) && !empty( $parent_def['parent_post_meta']) && !empty($parent_def['parent_post_meta']['product_weight']) ) {
340
							$cart_weight += ( $parent_def['parent_post_meta']['product_weight'] * $cart_item['item_qty'] );
341
						}
342
					}
343
				}
344 View Code Duplication
				else {
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...
345
					$product_data = get_post_meta( $cart_item['item_id'], '_wpshop_product_metadata', true );
346
					if ( !empty($product_data) && !empty($product_data['product_weight']) && !empty($cart_item['item_qty'])  ) {
347
						$cart_weight += ( $product_data['product_weight'] * $cart_item['item_qty'] );
348
					}
349
				}
350
			}
351
		}
352
		$cart_weight = apply_filters( 'extra_cart_weight_calcul', $cart_weight, $cart_items );
353
		return $cart_weight;
354
	}
355
356
357
}
358