Completed
Push — master ( e22a3b...731430 )
by Justin
06:54
created

form-validation.php ➔ wpsc_validate_form()   D

Complexity

Conditions 14
Paths 296

Size

Total Lines 71
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 14
eloc 40
c 3
b 1
f 0
nc 296
nop 2
dl 0
loc 71
rs 4.1552

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
function wpsc_validate_form( $form_args, &$validated_array = false ) {
4
	if ( ! is_array( $validated_array ) ) {
5
		$validated_array = &$_POST;
6
	}
7
8
	$error = new WP_Error();
9
	$a     =& $error;
10
11
	if ( ! isset( $form_args['fields'] ) ) {
12
		$valid = null;
13
	} else {
14
		$valid = true;
15
	}
16
17
	$form = $form_args['fields'];
18
19
	foreach ( $form as $props ) {
20
21
		// Handle custom fields.
22
		if ( ! isset( $props['fields'] ) ) {
23
			$props['fields'] = $props;
24
		}
25
26
		foreach ( $props['fields'] as $prop ) {
27
			if ( empty( $prop['rules'] ) ) {
28
				continue;
29
			}
30
31
			$prop = _wpsc_populate_field_default_args( $prop );
32
			$field = $prop['name'];
33
			$rules = $prop['rules'];
34
35
			if ( is_string( $rules ) ) {
36
				$rules = explode( '|', $rules );
37
			}
38
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
39
40
			$value = wpsc_submitted_value( $field, '', $validated_array );
41
42
			foreach ( $rules as $rule ) {
43
				if ( function_exists( $rule ) ) {
44
					$value = call_user_func( $rule, $value );
45
					continue;
46
				}
47
48
				if ( preg_match( '/([^\[]+)\[([^\]]+)\]/', $rule, $matches ) ) {
49
					$rule          = $matches[1];
50
					$matched_field = $matches[2];
51
					$matched_value = wpsc_submitted_value( $matched_field, null, $validated_array );
52
					$matched_props = isset( $form[$matched_field] ) ? $form[$matched_field] : array();
53
54
					$error = apply_filters( "wpsc_validation_rule_{$rule}", $error, $value, $field, $prop, $matched_field, $matched_value, $matched_props );
55
				} else {
56
					$error = apply_filters( "wpsc_validation_rule_{$rule}", $error, $value, $field, $prop );
57
				}
58
59
				if ( count( $error->get_error_codes() ) ) {
60
					break;
61
				}
62
			}
63
		}
64
65
		_wpsc_set_submitted_value( $field, $value, $validated_array );
0 ignored issues
show
Bug introduced by
The variable $field 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...
Bug introduced by
The variable $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...
66
	}
67
68
	if ( count( $error->get_error_messages() ) ) {
69
		$valid = $error;
70
	}
71
72
	return apply_filters( 'wpsc_validate_form', $valid );
73
}
74
75
/**
76
 * This is messy.
77
 *
78
 * @param  [type] $name  [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" 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...
79
 * @param  [type] $value [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" 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...
80
 * @param  [type] $from  [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" 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...
81
 * @return [type]        [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" 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...
82
 */
83
function _wpsc_set_submitted_value( $name, $value, &$from = null ) {
84
85
	if ( ! is_array ( $from ) ) {
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
86
		$from =& $_REQUEST;
87
	}
88
89
	$i = strpos( $name, '[' );
90
91
	if ( $i !== false ) {
92
		$head = substr( $name, 0, $i );
93
		preg_match_all( '/\[([^\]]+)\]/', $name, $matches );
94
		$matches = $matches[1];
95
		array_unshift( $matches, $head );
96
97
		$val = &$from;
98
99
		foreach ( $matches as $token ) {
100
			if ( array_key_exists( $token, $val ) )
101
				$val = &$val[ $token ];
102
			else
103
				return;
104
		}
105
		return;
106
	}
107
108
	$from[ $name ] = $value;
109
}
110
111
function wpsc_validation_rule_required( $error, $value, $field, $props ) {
112
	if ( $value === '' ) {
113
		$error_message = apply_filters( 'wpsc_validation_rule_required_message', __( 'The %s field is empty.', 'wp-e-commerce' ), $value, $field, $props );
114
		$title = isset( $props['title_validation'] ) ? $props['title_validation'] : $field;
115
		$error->add( $field, sprintf( $error_message, $title ), array( 'value' => $value, 'props' => $props ) );
116
	}
117
118
	return $error;
119
}
120
121
add_filter( 'wpsc_validation_rule_required', 'wpsc_validation_rule_required', 10, 4 );
122
123
function _wpsc_filter_terms_conditions_required_message( $message, $value, $field, $props ) {
0 ignored issues
show
Unused Code introduced by
The parameter $value 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...
Unused Code introduced by
The parameter $field 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...
124
	if ( $props['name'] == 'wpsc_terms_conditions' )
125
		$message = __( 'You are required to agree to our <a class="thickbox" target="_blank" href="%s" class="termsandconds">Terms and Conditions</a> in order to proceed with checkout.', 'wp-e-commerce' );
126
127
	return $message;
128
}
129
130
add_filter( 'wpsc_validation_rule_required_message', '_wpsc_filter_terms_conditions_required_message', 10, 4 );
131
132
function wpsc_validation_rule_email( $error, $value, $field, $props ) {
133
	$field_title = isset( $props['title_validation'] ) ? $props['title_validation'] : $field;
134
135
	if ( empty( $value ) ) {
136
		return $error;
137
	}
138
139
	if ( ! is_email( $value ) ) {
140
		$message = apply_filters( 'wpsc_validation_rule_invalid_email_message', __( 'The %s field contains an invalid email address.', 'wp-e-commerce' ) );
141
		$error->add( $field, sprintf( $message, $field_title ), array( 'value' => $value, 'props' => $props ) );
142
	}
143
144
	return $error;
145
}
146
add_filter( 'wpsc_validation_rule_email', 'wpsc_validation_rule_email', 10, 4 );
147
148
function wpsc_validation_rule_valid_username_or_email( $error, $value, $field, $props ) {
149
	if ( strpos( $value, '@' ) ) {
150
		$user = get_user_by( 'email', $value );
151
		if ( empty( $user ) ) {
152
			$message = apply_filters( 'wpsc_validation_rule_account_email_not_found_message', __( 'There is no user registered with that email address.', 'wp-e-commerce' ), $value, $field, $props );
153
			$error->add( $field, $message, array( 'value' => $value, 'props' => $props) );
154
		}
155
	} else {
156
		$user = get_user_by( 'login', $value );
157
		if ( empty( $user ) ) {
158
			$message = apply_filters( 'wpsc_validation_rule_username_not_found_message', __( 'There is no user registered with that username.', 'wp-e-commerce' ), $value, $field, $props );
159
			$error->add( $field, $message, array( 'value' => $value, 'props' => $props ) );
160
		}
161
	}
162
163
	return $error;
164
}
165
add_filter( 'wpsc_validation_rule_valid_username_or_email', 'wpsc_validation_rule_valid_username_or_email', 10, 4 );
166
167
function wpsc_validation_rule_matches( $error, $value, $field, $props, $matched_field, $matched_value, $matched_props ) {
168
	if ( is_null( $matched_value ) || $value != $matched_value ) {
169
		$message = apply_filters( 'wpsc_validation_rule_fields_dont_match_message', __( 'The %s and %s fields do not match.', 'wp-e-commerce' ), $value, $field, $props, $matched_field, $matched_value, $matched_props );
170
		$title = isset( $props['title_validation'] ) ? $props['title_validation'] : $field;
171
		$matched_title = isset( $matched_props['title_validation'] ) ? $matched_props['title_validation'] : $field;
172
		$error->add( $field, sprintf( $message, $title, $matched_title ), array( 'value' => $value, 'props' => $props ) );
173
	}
174
175
	return $error;
176
}
177
add_filter( 'wpsc_validation_rule_matches', 'wpsc_validation_rule_matches', 10, 7 );
178
179
function wpsc_validation_rule_username( $error, $value, $field, $props ) {
180
	$field_title = isset( $props['title_validation'] ) ? $props['title_validation'] : $field;
181
182
	if ( ! validate_username( $value ) ) {
183
		$message = apply_filters( 'wpsc_validation_rule_invalid_username_message', __( 'This %s contains invalid characters. Username may contain letters (a-z), numbers (0-9), dashes (-), underscores (_) and periods (.).', 'wp-e-commerce' ) );
184
		$error->add( $field, sprintf( $message, $field_title ), array( 'value' => $value, 'props' => $props ) );
185
	} elseif ( username_exists( $value ) ) {
186
		$message = apply_filters( 'wpsc_validation_rule_username_not_available_message', _x( 'This %s is already used by another account. Please choose another one.', 'username not available', 'wp-e-commerce' ) );
187
		$error->add( $field, sprintf( $message, $field_title ), array( 'value' => $value, 'props' => $props ) );
188
	}
189
190
	return $error;
191
}
192
add_filter( 'wpsc_validation_rule_username', 'wpsc_validation_rule_username', 10, 4 );
193
194
function wpsc_validation_rule_account_email( $error, $value, $field, $props ) {
195
	$field_title = isset( $props['title_validation'] ) ? $props['title_validation'] : $field;
196
197
	if ( ! is_email( $value ) ) {
198
		$message = apply_filters( 'wpsc_validation_rule_invalid_account_email_message', __( 'The %s is not valid.', 'wp-e-commerce' ) );
199
		$error->add( $field, sprintf( $message, $field_title ), array( 'value' => $value, 'props' => $props ) );
200
	} elseif ( email_exists( $value ) ) {
201
		$message = apply_filters( 'wpsc_validation_rule_account_email_not_available_message', _x( 'This %s is already used by another account. Please choose another one.', 'email not available', 'wp-e-commerce' ) );
202
		$error->add( $field, sprintf( $message, $field_title ), array( 'value' => $value, 'props' => $props ) );
203
	}
204
205
	return $error;
206
}
207
add_filter( 'wpsc_validation_rule_account_email', 'wpsc_validation_rule_account_email', 10, 4 );
208
209
function _wpsc_filter_validation_rule_state_of( $error, $value, $field, $props, $matched_field, $matched_value, $matched_props ) {
0 ignored issues
show
Unused Code introduced by
The parameter $matched_value 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...
Unused Code introduced by
The parameter $matched_props 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...
210
	global $wpdb;
211
212
	if ( $value == '' ) {
213
		return $error;
214
	}
215
216
	$country_code = $_POST['wpsc_checkout_details'][ $matched_field ];
217
	$country      = new WPSC_Country( $country_code );
218
219
	if ( ! $country->has_regions() ) {
220
		return $error;
221
	}
222
223
	// state should have been converted into a numeric value already
224
	// if not, it's an invalid state
225
	if ( ! is_numeric( $value ) ) {
226
		$message = apply_filters(
227
			'wpsc_validation_rule_invalid_state_message',
228
			/* translators: %1$s is state, %2$s is country */
229
			__( '%1$s is not a valid state or province in %2$s', 'wp-e-commerce' )
230
		);
231
		$message = sprintf( $message, $value, $country->get_name() );
232
		$error->add(
233
			$field,
234
			$message,
235
			array(
236
				'value' => $value,
237
				'props' => $props,
238
			)
239
		);
240
241
		return $error;
242
	}
243
244
	$sql   = $wpdb->prepare('SELECT COUNT(id) FROM ' . WPSC_TABLE_REGION_TAX . ' WHERE id = %d', $value );
245
	$count = $wpdb->get_var( $sql );
246
247
	if ( $count == 0 ) {
248
		$message = apply_filters(
249
			'wpsc_validation_rule_invalid_state_id_message',
250
			__( 'You specified or were assigned an invalid state or province. Please contact administrator for assistance', 'wp-e-commerce' )
251
		);
252
		$error->add(
253
			$field,
254
			$message,
255
			array(
256
				'value' => $value,
257
				'props' => $props,
258
			)
259
		);
260
	}
261
262
	return $error;
263
}
264
265
add_filter( 'wpsc_validation_rule_state_of', '_wpsc_filter_validation_rule_state_of', 10, 7 );
266
267
function _wpsc_convert_state( $state ) {
268
	global $wpdb;
269
270
	if ( is_numeric( $state ) ) {
271
		return (int) $state;
272
	}
273
274
	if ( strlen( $state ) == 2 ) {
275
		$where = 'code = %s';
276
	} else {
277
		$where = 'name = %s';
278
	}
279
280
	$sql = $wpdb->prepare( 'SELECT id FROM ' . WPSC_TABLE_REGION_TAX . ' WHERE ' . $where, $state );
281
	$val = $wpdb->get_var( $sql );
282
283
	if ( $val ) {
284
		$state = (int) $val;
285
	}
286
287
	return $state;
288
}
289