Skip to content

Commit 449ea64

Browse files
committed
Sniff::is_validated(): recognize null coalesce (equal) operator as a way to validate a variable
This adds recognition of the coalesce operator `??` (PHP 7.0) and the coalesce equals operator `??=`, as will be added in PHP 7.4, to the `Sniff::is_validated()` method. This prevents false positives where variables would be seen as "not validated", when the variable has in fact been validated via a coalesce equals assignment in a previous statement. Related to 764, 840
1 parent 6c8d052 commit 449ea64

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

WordPress/Sniff.php

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2097,10 +2097,12 @@ protected function is_validated( $stackPtr, $array_keys = array(), $in_condition
20972097

20982098
$bare_array_keys = array_map( array( $this, 'strip_quotes' ), $array_keys );
20992099
$targets = array(
2100-
\T_ISSET => 'construct',
2101-
\T_EMPTY => 'construct',
2102-
\T_UNSET => 'construct',
2103-
\T_STRING => 'function_call',
2100+
\T_ISSET => 'construct',
2101+
\T_EMPTY => 'construct',
2102+
\T_UNSET => 'construct',
2103+
\T_STRING => 'function_call',
2104+
\T_COALESCE => 'coalesce',
2105+
\T_COALESCE_EQUAL => 'coalesce',
21042106
);
21052107

21062108
// phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer.Found -- On purpose, see below.
@@ -2215,6 +2217,40 @@ protected function is_validated( $stackPtr, $array_keys = array(), $in_condition
22152217
}
22162218

22172219
return true;
2220+
2221+
case 'coalesce':
2222+
$prev = $i;
2223+
do {
2224+
$prev = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $prev - 1 ), null, true, null, true );
2225+
// Skip over array keys, like $_GET['key']['subkey'].
2226+
if ( \T_CLOSE_SQUARE_BRACKET === $this->tokens[ $prev ]['code'] ) {
2227+
$prev = $this->tokens[ $prev ]['bracket_opener'];
2228+
continue;
2229+
}
2230+
2231+
break;
2232+
} while ( $prev >= ( $scope_start + 1 ) );
2233+
2234+
// We should now have reached the variable.
2235+
if ( \T_VARIABLE !== $this->tokens[ $prev ]['code'] ) {
2236+
continue 2;
2237+
}
2238+
2239+
if ( $this->tokens[ $prev ]['content'] !== $this->tokens[ $stackPtr ]['content'] ) {
2240+
continue 2;
2241+
}
2242+
2243+
if ( ! empty( $bare_array_keys ) ) {
2244+
$found_keys = $this->get_array_access_keys( $prev );
2245+
$found_keys = array_map( array( $this, 'strip_quotes' ), $found_keys );
2246+
$diff = array_diff_assoc( $bare_array_keys, $found_keys );
2247+
if ( ! empty( $diff ) ) {
2248+
continue 2;
2249+
}
2250+
}
2251+
2252+
// Right variable, correct key.
2253+
return true;
22182254
}
22192255
}
22202256

0 commit comments

Comments
 (0)