Completed
Push — master ( 88dfbf...b0f2bc )
by
unknown
12:27
created

wpshop_cart_rules::admin_css()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php if ( !defined( 'ABSPATH' ) ) exit;
2
3
/**
4
 * Cart rules bootstrap file
5
 * @author Jérôme ALLEGRE - Eoxia dev team <[email protected]>
6
 * @version 0.1
7
 * @package includes
8
 * @subpackage modules
9
 *
10
 */
11
12
if ( !defined( 'WPSHOP_VERSION' ) ) {
13
	die( __("You are not allowed to use this service.", 'wpshop') );
14
}
15
if ( !class_exists("wpshop_cart_rules") ) {
16
	class wpshop_cart_rules {
17
18
		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...
19
			/**	Add module option to wpshop general options	*/
20
			add_filter('wpshop_options', array(&$this, 'add_options'), 9);
21
			add_action('wsphop_options', array(&$this, 'declare_options'));
22
23
			add_filter( 'wpshop_custom_template', array( &$this, 'custom_template_load' ) );
24
25
			/**	Include the different javascript & style	*/
26
			//add_action( 'init', array(&$this, 'frontend_js') );
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
27
			add_action( 'admin_enqueue_scripts', array(&$this, 'admin_scripts') );
28
29
			/** AJAX actions **/
30
			add_action('wp_ajax_save_cart_rule',array( $this, 'wpshop_ajax_save_cart_rule'));
31
			add_action('wp_ajax_delete_cart_rule',array( $this, 'wpshop_ajax_delete_cart_rule'));
32
		}
33
34
		/**
35
		 * Load the different javascript librairies
36
		 */
37
		// function frontend_js() {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
38
		// 	/** JS Include **/
39
		// 	wp_enqueue_script("jquery");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
40
		// }
41
		/**
42
		 * Load the different javascript librairies
43
		 */
44
		function admin_scripts( $hook ) {
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...
45
			if ( $hook != 'settings_page_wpshop_option' )
46
				return;
47
48
			/** JS Include **/
49
			wp_enqueue_script("jquery");
50
			wp_enqueue_script( 'wpshop_cart_rules', plugins_url('templates/backend/js/wpshop_cart_rules.js', __FILE__) );
51
			/** CSS Include **/
52
			wp_register_style( 'wpshop_cart_rules_css', plugins_url('templates/backend/css/wpshop_cart_rules.css', __FILE__) );
53
			wp_enqueue_style( 'wpshop_cart_rules_css' );
54
		}
55
56
		/** Load the module template **/
57
		function custom_template_load( $templates ) {
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...
58
			include('templates/backend/main_elements.tpl.php');
59
60
			foreach ( $tpl_element as $template_part => $template_part_content) {
0 ignored issues
show
Bug introduced by
The variable $tpl_element does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
61 View Code Duplication
				foreach ( $template_part_content as $template_type => $template_type_content) {
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...
62
					foreach ( $template_type_content as $template_key => $template) {
63
						$templates[$template_part][$template_type][$template_key] = $template;
64
					}
65
				}
66
			}
67
			unset($tpl_element);
68
69
			return $templates;
70
		}
71
72
		/** Declare options for this module **/
73
		function declare_options () {
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...
74
			if ( WPSHOP_DEFINED_SHOP_TYPE == 'sale' ) {
75
				$wpshop_shop_type = !empty( $_POST['wpshop_shop_type'] ) ? sanitize_text_field( $_POST['wpshop_shop_type'] ) : '';
76
				$old_wpshop_shop_type = !empty( $_POST['old_wpshop_shop_type'] ) ? sanitize_text_field( $_POST['old_wpshop_shop_type'] ) : '';
77
78
				if ( ( $wpshop_shop_type == '' || $wpshop_shop_type != 'presentation' )
79
					&& ( $old_wpshop_shop_type == '' || $old_wpshop_shop_type != 'presentation' ) ) {
80
						add_settings_section('wpshop_cart_rules_option', '<span class="dashicons dashicons-cart"></span>'.__('Cart Rules', 'wpshop'), array(&$this, 'cart_rules_section_text'), 'wpshop_cart_rules_option');
81
						register_setting('wpshop_options', 'wpshop_cart_rules_option', array(&$this, 'validate_cart_rules_options'));
82
						add_settings_field('wpshop_cart_rules_option', __('Activate cart rules', 'wpshop'), array(&$this, 'wpshop_cart_rules_field'), 'wpshop_cart_rules_option', 'wpshop_cart_rules_option');
83
84
					}
85
			}
86
		}
87
88
		/** Add a section for option display **/
89
		function add_options( $option_group ) {
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...
90
			$option_group['wpshop_cart_option']['subgroups']['wpshop_cart_rules_option']['class'] = ' wpshop_admin_box_options_cart_rules';
91
			return $option_group;
92
		}
93
94
		function cart_rules_section_text () {
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...
95
96
		}
97
98
		/** Option cart rules configuuration interface **/
99
		function wpshop_cart_rules_field () {
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...
100
			global $wpdb;
101
			$cart_rules_options = get_option('wpshop_cart_rules_option');
102
			$cart_rules = ( !empty($cart_rules_options) ) ? $cart_rules_options['rules'] : '';
103
104
			$wpshop_customer_groups = get_option('wp_user_roles');
105
106
			$tpl_component['CART_RULES_CUSTOMERS_GROUPS'] = '<option value="">' .__('All customers groups' , 'wpshop'). '</option>';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tpl_component was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tpl_component = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
107
			if ( !empty($wpshop_customer_groups) ) {
108
				foreach ( $wpshop_customer_groups as $k =>  $wpshop_customer_group) {
0 ignored issues
show
Bug introduced by
The expression $wpshop_customer_groups of type string is not traversable.
Loading history...
109
					$tpl_component['CART_RULES_CUSTOMERS_GROUPS'] .= '<option value="' .$k. '">' .$wpshop_customer_group['name']. '</option>';
110
				}
111
			}
112
113
			$tpl_component['CART_RULES_DATA'] = ( !empty($cart_rules) ) ? $cart_rules : '';
114
			$tpl_component['ACTIVE_CART_RULES'] = ( (!empty($cart_rules_options) && !empty($cart_rules_options['activate']) ) ? 'checked="checked"' : '');
115
116
			$tpl_component['ALL_CART_RULES'] = (!empty($cart_rules) ) ? wpshop_cart_rules::display_cart_rules( $cart_rules ) : '';
117
			$tpl_component['MEDIAS_ICON_URL'] = WPSHOP_MEDIAS_ICON_URL;
118
			/** Product list **/
119
			$query = $wpdb->prepare('SELECT ID, post_title, post_type FROM '.$wpdb->posts.' WHERE (post_type = %s OR post_type = %s) AND (post_status = %s OR post_status = %s)', WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT, WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION, 'draft', 'publish');
120
			$products = $wpdb->get_results($query);
121
			$tpl_component['PRODUCTS_LIST_FOR_GIFT'] = '';
122
			if ( !empty($products) ) {
123
				foreach($products as $product) {
124
					if ( $product->post_type == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION ) {
125
						$parent_product_infos = wpshop_products::get_parent_variation ( $product->ID );
126
						if ( !empty($parent_product_infos) && !empty($parent_product_infos['parent_post']) ) {
127
							$parent_post_infos = $parent_product_infos['parent_post'];
128
							$product_title = $parent_post_infos->post_title;
129
130
							$product_options = get_post_meta($product->ID, '_wpshop_variations_attribute_def', true);
131
							if ( !empty($product_options) && is_array($product_options) ) {
132
								$option_name = '';
133 View Code Duplication
								foreach( $product_options as $k=>$product_option) {
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...
134
									$query = $wpdb->prepare('SELECT frontend_label FROM '.WPSHOP_DBT_ATTRIBUTE.' WHERE code = %s', $k);
135
									$option_name .= $wpdb->get_var($query).' ';
136
									$query = $wpdb->prepare('SELECT label FROM '.WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS.' WHERE id= %d', $product_option);
137
									$option_name .=  $wpdb->get_var($query).' ';
138
								}
139
								$tpl_component['PRODUCTS_LIST_FOR_GIFT'] .= '<option value="'.$product->ID. '" >'. $product_title .' (' .$option_name. ')</option>';
140
							}
141
142
						}
143
					}
144
					else {
145
						$tpl_component['PRODUCTS_LIST_FOR_GIFT'] .= '<option value="'.$product->ID. '" >' .$product->post_title. '</option>';
146
					}
147
				}
148
			}
149
150
			$output = wpshop_display::display_template_element('cart_rules_interface', $tpl_component, array(), 'admin');
151
			unset($tpl_component);
152
			echo $output;
153
		}
154
155
		function validate_cart_rules_options ($input) {
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...
156
			return $input;
157
		}
158
159
		/** Save the cart rule **/
160
		function wpshop_ajax_save_cart_rule () {
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...
161
			$_wpnonce = !empty( $_POST['_wpnonce'] ) ? sanitize_text_field( $_POST['_wpnonce'] ) : '';
162
163
			if ( !wp_verify_nonce( $_wpnonce, 'wpshop_ajax_save_cart_rule' ) )
164
				wp_die();
165
166
			$cart_limen = ( !empty($_POST['cart_limen']) ) ? wpshop_tools::varSanitizer($_POST['cart_limen']) : null;
167
			$discount_type = ( !empty($_POST['discount_type']) ) ? wpshop_tools::varSanitizer($_POST['discount_type']) : null;
168
			$discount_value = ( !empty($_POST['discount_value']) ) ? wpshop_tools::varSanitizer($_POST['discount_value']) : null;
169
			$customer_groups = wpshop_tools::varSanitizer($_POST['customer_groups']);
170
171
			$status = false;
172
			$response = array();
0 ignored issues
show
Unused Code introduced by
$response 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...
173
			$cart_rules = ( !empty($_POST['cart_rules']) ) ? sanitize_text_field( $_POST['cart_rules'] ) : null;
174
175
			if ( !empty($cart_limen) && !empty($discount_type) && !empty($discount_value) ) {
176
				if ( !empty($cart_rules) ) {
177
					$cart_rules = unserialize(stripslashes($cart_rules));
178
					$cart_rules[$cart_limen] = array('discount_type' => $discount_type, 'discount_value' => $discount_value, 'customer_group' => $customer_groups);
179
180
				}
181
				else {
182
					$cart_rules = array();
183
					$cart_rules[$cart_limen] = array('discount_type' => $discount_type, 'discount_value' => $discount_value, 'customer_group' => $customer_groups);
184
				}
185
				$cart_rules = serialize($cart_rules);
186
				$status = true;
187
			}
188
189
			$display_rules = wpshop_cart_rules::display_cart_rules($cart_rules);
190
			$reponse = array('status' => $status, 'response' => $cart_rules, 'display_rules' => $display_rules);
191
			echo json_encode($reponse);
192
			die();
193
		}
194
195
		/** Save the cart rule **/
196
		function wpshop_ajax_delete_cart_rule () {
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...
197
			$_wpnonce = !empty( $_POST['_wpnonce'] ) ? sanitize_text_field( $_POST['_wpnonce'] ) : '';
198
199
			if ( !wp_verify_nonce( $_wpnonce, 'wpshop_ajax_delete_cart_rule' ) )
200
				wp_die();
201
202
			$cart_rule_id = ( !empty($_POST['cart_rule_id']) ) ? wpshop_tools::varSanitizer($_POST['cart_rule_id']) : null;
203
204
			$status = false;
205
			$response = array();
0 ignored issues
show
Unused Code introduced by
$response 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...
206
			$cart_rules = ( !empty($_POST['cart_rules']) ) ? sanitize_text_field( $_POST['cart_rules'] ) : null;
207
208
			$cart_rule_id = str_replace('_', '.', $cart_rule_id);
209
210
			if ( !empty($cart_rule_id) ) {
211
				$cart_rules = unserialize(stripslashes($cart_rules));
212
				unset($cart_rules[$cart_rule_id]);
213
				$cart_rules = serialize($cart_rules);
214
				$status = true;
215
			}
216
			$display_rules = wpshop_cart_rules::display_cart_rules($cart_rules);
0 ignored issues
show
Unused Code introduced by
$display_rules 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...
217
218
			$display_rules = wpshop_cart_rules::display_cart_rules($cart_rules);
219
			$reponse = array('status' => $status, 'response' => $cart_rules, 'display_rules' => $display_rules);
220
			echo json_encode($reponse);
221
			die();
222
		}
223
224
		/** Display all cart rules **/
225
		function display_cart_rules( $rules ) {
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...
226
			global $wpdb;
227
			$output = '';
228
			if ( !empty($rules) ) {
229
				$tpl_component['MEDIAS_ICON_URL'] = WPSHOP_MEDIAS_ICON_URL;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tpl_component was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tpl_component = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
230
				$tpl_component['CART_RULES_LINE'] = '';
231
				foreach( unserialize($rules) as $k => $rule ) {
232
					$sub_tpl_component['CART_RULE_LINE_CART_LIMEN'] = $k;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sub_tpl_component was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sub_tpl_component = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
233
					switch ($rule['discount_type']) {
234
						case 'absolute_discount' :
235
							$discount_type = __('Absolute discount', 'wpshop');
236
							$discount_value = $rule['discount_value'].' '.wpshop_tools::wpshop_get_currency();
237
						break;
238
						case 'percent_discount' :
239
							$discount_type = __('Percent discount', 'wpshop');
240
							$discount_value = $rule['discount_value'].' %';
241
						break;
242
						case 'gift_product' :
243
							$discount_type = __('Product gift', 'wpshop');
244
							$product = get_post( $rule['discount_value'] );
245
							if ( $product->post_type == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION ) {
246
								$parent_product_infos = wpshop_products::get_parent_variation ( $product->ID );
247
								if ( !empty($parent_product_infos) && !empty($parent_product_infos['parent_post']) ) {
248
									$parent_post_infos = $parent_product_infos['parent_post'];
249
									$product_title = $parent_post_infos->post_title;
250
251
									$product_options = get_post_meta($product->ID, '_wpshop_variations_attribute_def', true);
252
									if ( !empty($product_options) && is_array($product_options) ) {
253
										$option_name = '';
254 View Code Duplication
										foreach( $product_options as $k=>$product_option) {
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...
255
											$query = $wpdb->prepare('SELECT frontend_label FROM '.WPSHOP_DBT_ATTRIBUTE.' WHERE code = %s', $k);
256
											$option_name .= $wpdb->get_var($query).' ';
257
											$query = $wpdb->prepare('SELECT label FROM '.WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS.' WHERE id= %d', $product_option);
258
											$option_name .=  $wpdb->get_var($query).' ';
259
										}
260
										$discount_value = $product_title .' (' .$option_name. ')';
261
									}
262
263
								}
264
							}
265
							else {
266
								$discount_value = $product->post_title;
267
							}
268
						break;
269
						default :
270
							$discount_type = '';
271
							$discount_value = $rule['discount_value'];
272
						break;
273
					}
274
					$sub_tpl_component['CART_RULE_LINE_DISCOUNT_TYPE'] = $discount_type;
0 ignored issues
show
Bug introduced by
The variable $sub_tpl_component 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...
275
					$sub_tpl_component['CART_RULE_LINE_DISCOUNT_VALUE'] = $discount_value;
0 ignored issues
show
Bug introduced by
The variable $discount_value 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...
276
					$sub_tpl_component['CART_RULE_LINE_CUSTOMER_GROUP'] = (!empty($rule['customer_group']) ) ? $rule['customer_group'] : __('All customers groups', 'wpshop');
277
					$sub_tpl_component['CART_RULE_ID'] = str_replace('.', '_', $sub_tpl_component['CART_RULE_LINE_CART_LIMEN']);
278
					$sub_tpl_component['MEDIAS_ICON_URL'] = WPSHOP_MEDIAS_ICON_URL;
279
					$tpl_component['CART_RULES_LINE'] .= wpshop_display::display_template_element('cart_rules_line', $sub_tpl_component, array(), 'admin');
280
					unset($sub_tpl_component);
281
				}
282
				$output = wpshop_display::display_template_element('cart_rules_display', $tpl_component, array(), 'admin');
283
			}
284
			return $output;
285
		}
286
287
		/**
288
		 * Check if a cart rule exist for a cart amount
289
		 * @param integer_type $cart_amount
290
		 * @return array
291
		 */
292
		public static function get_cart_rule ($cart_amount) {
293
			$cart_rule_info = array();
294
			$cart_rule_exist = false;
295
			if ( !empty($cart_amount) ) {
296
				$cart_rules_option = get_option('wpshop_cart_rules_option');
297
				if ( !empty($cart_rules_option) && !empty($cart_rules_option['activate']) && !empty($cart_rules_option['rules']) ) {
298
					$cart_rules = unserialize($cart_rules_option['rules']);
299
					if ( is_array($cart_rules) ) {
300
						$cart_rule_id = 0;
0 ignored issues
show
Unused Code introduced by
$cart_rule_id 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...
301
						foreach( $cart_rules as $k => $cart_rule ) {
302
							if ( $cart_amount >= $k ) {
303
								$cart_rule_id = $k;
304
								if ( $cart_rule_id != 0 ) {
305
									/** Check if there is a customer group limit **/
306
									if ( empty($cart_rules[$cart_rule_id]['customer_group']) ) {
307
										$cart_rule_exist = true;
308
										$cart_rule_info['discount_type'] = $cart_rules[$cart_rule_id]['discount_type'];
309
										$cart_rule_info['discount_value'] = $cart_rules[$cart_rule_id]['discount_value'];
310
									}
311
									else {
312
										if ( get_current_user_id() != 0 ) {
313
											$user_meta = get_user_meta( get_current_user_id(), 'wp_capabilities', true );
314
											if ( !empty($user_meta)  ) {
315
												foreach ($user_meta as $k => $user) {
316
													if ( $k == $cart_rules[$cart_rule_id]['customer_group'] ) {
317
														$cart_rule_exist = true;
318
														$cart_rule_info['discount_type'] = $cart_rules[$cart_rule_id]['discount_type'];
319
														$cart_rule_info['discount_value'] = $cart_rules[$cart_rule_id]['discount_value'];
320
													}
321
												}
322
											}
323
										}
324
									}
325
326
								}
327
							}
328
						}
329
					}
330
				}
331
			}
332
			return array('cart_rule_exist' => $cart_rule_exist, 'cart_rule_info' => $cart_rule_info);
333
		}
334
335
		function add_gift_product_to_cart ( $cartContent, $order ) {
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...
336
			global $wpdb;
337
			if ( !empty($order['cart_rule']) && !empty($order['cart_rule']['discount_value']) && !empty($order['cart_rule']['discount_type']) &&  $order['cart_rule']['discount_type'] == 'gift_product') {
338
				$product = get_post( $order['cart_rule']['discount_value'] );
339
				$option_name = '';
340
				if ( $product->post_type == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION ) {
341
					$parent_product_infos = wpshop_products::get_parent_variation ( $product->ID );
342
					if ( !empty($parent_product_infos) && !empty($parent_product_infos['parent_post']) ) {
343
						$parent_post_infos = $parent_product_infos['parent_post'];
344
						$product_title = $parent_post_infos->post_title;
345
346
						$product_options = get_post_meta($product->ID, '_wpshop_variations_attribute_def', true);
347
						if ( !empty($product_options) && is_array($product_options) ) {
348
							$option_name = '';
349 View Code Duplication
							foreach( $product_options as $k=>$product_option) {
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...
350
								$query = $wpdb->prepare('SELECT frontend_label FROM '.WPSHOP_DBT_ATTRIBUTE.' WHERE code = %s', $k);
351
								$option_name .= $wpdb->get_var($query).' ';
352
								$query = $wpdb->prepare('SELECT label FROM '.WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS.' WHERE id= %d', $product_option);
353
								$option_name .=  $wpdb->get_var($query).' ';
354
							}
355
							$discount_value = $product_title ;
356
						}
357
358
					}
359
				}
360
				else {
361
					$discount_value = $product->post_title;
362
				}
363
364
				$tpl_component['CART_PRODUCT_MORE_INFO'] = $option_name;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tpl_component was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tpl_component = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
365
				$tpl_component['CART_LINE_ITEM_ID'] = $order['cart_rule']['discount_value'];
366
				$tpl_component['CART_LINE_ITEM_PUHT'] = number_format(0, 2);
367
				$tpl_component['CART_LINE_ITEM_DISCOUNT_AMOUNT'] = number_format(0, 2);
368
				$tpl_component['CART_LINE_ITEM_TPHT'] = number_format(0, 2);
369
				$tpl_component['CART_LINE_ITEM_TPTTC'] = number_format(0, 2);
370
371
				$tpl_component['CART_LINE_ITEM_QTY_'] = 1;
372
				$tpl_component['CART_LINE_ITEM_REMOVER'] = '';
373
				$tpl_component['CART_PRODUCT_NAME'] = $discount_value .' ('.__('Gift product', 'wpshop').')';
0 ignored issues
show
Bug introduced by
The variable $discount_value 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...
374
375
376
				$cartContent .= wpshop_display::display_template_element('cart_line', $tpl_component);
377
378
			}
379
			return $cartContent;
380
		}
381
	}
382
}
383
/**	Instanciate the module utilities if not	*/
384
if ( class_exists("wpshop_cart_rules") ) {
385
	$wpshop_cart_rules = new wpshop_cart_rules();
386
}
387