Skip to content

Commit

Permalink
Merge pull request #324 from jrfnl/feature/fix-text-string-handling-preg
Browse files Browse the repository at this point in the history
Improve how string tokens are dealt with in PregReplaceEModifierSniff.
  • Loading branch information
wimg committed Jan 3, 2017
2 parents 6138df0 + d1f5199 commit 4853c6d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
7 changes: 6 additions & 1 deletion Sniffs/PHP/PregReplaceEModifierSniff.php
Expand Up @@ -129,7 +129,12 @@ protected function processRegexPattern($pattern, $phpcsFile, $stackPtr, $functio
$regex = '';
for ($i = $pattern['start']; $i <= $pattern['end']; $i++ ) {
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$stringTokens, true) === true) {
$regex .= $this->stripQuotes($tokens[$i]['content']);
$content = $this->stripQuotes($tokens[$i]['content']);
if ($tokens[$i]['code'] === T_DOUBLE_QUOTED_STRING) {
$content = $this->stripVariables($content);
}

$regex .= trim($content);
}
}
// Deal with multi-line regexes which were broken up in several string tokens.
Expand Down
7 changes: 7 additions & 0 deletions Tests/Sniffs/PHP/PregReplaceEModifierSniffTest.php
Expand Up @@ -99,6 +99,10 @@ public function dataDeprecatedEModifier() {
array(177),

array(182), // Three errors.

// Interpolated variables.
array(204),
array(205),
);
}

Expand Down Expand Up @@ -166,6 +170,9 @@ public function dataNoViolation() {
array(178),
array(187),
array(201),

// Interpolated variables.
array(206),
);
}

Expand Down
5 changes: 5 additions & 0 deletions Tests/sniff-examples/preg_replace_e_modifier.php
Expand Up @@ -199,3 +199,8 @@ function XRegeXe() {
// Another false positive.
// https://wordpress.org/support/topic/wrong-error-preg_replace-e-modifier-is-forbidden-since-php-7-0/
$this->value = preg_replace( $this->field['preg']['pattern'], $this->field['preg']['replacement'], $this->value );

// Deal correctly with interpolated strings.
preg_replace("/dou$ble-quoted/e", $Replace, $Source); // Bad.
preg_replace("/dou$ble-quoted/me$me", $Replace, $Source); // Bad.
preg_replace("/double-quoted/$e", $Replace, $Source); // Ok.

0 comments on commit 4853c6d

Please sign in to comment.