Skip to content

Commit 7c6f0a8

Browse files
committed
ValidatedSanitizedInput: allow for validation via null coalesce / null coalesce equals
PHP 7.0 introduced the null coalesce operator, while PHP 7.4 will introduce the null coalesce equal operator. These operators should be accounted for in the `ValidatedSanitizedInput` sniff as valid ways to validate a variable, but should still allow for the sniff to *also* check for sanitization. Refs: * https://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce * https://wiki.php.net/rfc/isset_ternary * https://wiki.php.net/rfc/null_coalesce_equal_operator Related to 764 Fixes 837 Closes 840 which is superseded by this PR
1 parent 625f221 commit 7c6f0a8

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
namespace WordPressCS\WordPress\Sniffs\Security;
1111

1212
use WordPressCS\WordPress\Sniff;
13+
use PHP_CodeSniffer\Util\Tokens;
1314

1415
/**
1516
* Flag any non-validated/sanitized input ( _GET / _POST / etc. ).
@@ -131,8 +132,37 @@ function ( $symbol ) {
131132

132133
$error_data = array( $this->tokens[ $stackPtr ]['content'] . '[' . implode( '][', $array_keys ) . ']' );
133134

134-
// Check for validation first.
135-
if ( ! $this->is_validated( $stackPtr, $array_keys, $this->check_validation_in_scope_only ) ) {
135+
/*
136+
* Check for validation first.
137+
*/
138+
$validated = false;
139+
140+
for ( $i = ( $stackPtr + 1 ); $i < $this->phpcsFile->numTokens; $i++ ) {
141+
if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) ) {
142+
continue;
143+
}
144+
145+
if ( \T_OPEN_SQUARE_BRACKET === $this->tokens[ $i ]['code']
146+
&& isset( $this->tokens[ $i ]['bracket_closer'] )
147+
) {
148+
// Skip over array keys.
149+
$i = $this->tokens[ $i ]['bracket_closer'];
150+
continue;
151+
}
152+
153+
if ( \T_COALESCE === $this->tokens[ $i ]['code'] ) {
154+
$validated = true;
155+
}
156+
157+
// Anything else means this is not a validation coalesce.
158+
break;
159+
}
160+
161+
if ( false === $validated ) {
162+
$validated = $this->is_validated( $stackPtr, $array_keys, $this->check_validation_in_scope_only );
163+
}
164+
165+
if ( false === $validated ) {
136166
$this->phpcsFile->addError(
137167
'Detected usage of a possibly undefined superglobal array index: %s. Use isset() or empty() to check the index exists before using it',
138168
$stackPtr,

0 commit comments

Comments
 (0)