From 326a8d23e984ad00d01cfde130607f6cc27e5580 Mon Sep 17 00:00:00 2001 From: ChrisDBrown Date: Wed, 30 Jun 2021 12:16:08 +0100 Subject: [PATCH] Support negative equality on StrEndsWith rule (#339) --- .../Fixture/substr_not_prefix.php.inc | 27 +++++++++++++++++++ .../Rector/Identical/StrEndsWithRector.php | 15 +++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 rules-tests/Php80/Rector/Identical/StrEndsWithRector/Fixture/substr_not_prefix.php.inc diff --git a/rules-tests/Php80/Rector/Identical/StrEndsWithRector/Fixture/substr_not_prefix.php.inc b/rules-tests/Php80/Rector/Identical/StrEndsWithRector/Fixture/substr_not_prefix.php.inc new file mode 100644 index 00000000000..2803c409047 --- /dev/null +++ b/rules-tests/Php80/Rector/Identical/StrEndsWithRector/Fixture/substr_not_prefix.php.inc @@ -0,0 +1,27 @@ + +----- + diff --git a/rules/Php80/Rector/Identical/StrEndsWithRector.php b/rules/Php80/Rector/Identical/StrEndsWithRector.php index ae2baa9c069..4dd8f51ec0b 100644 --- a/rules/Php80/Rector/Identical/StrEndsWithRector.php +++ b/rules/Php80/Rector/Identical/StrEndsWithRector.php @@ -9,6 +9,7 @@ use PhpParser\Node\Expr; use PhpParser\Node\Expr\BinaryOp; use PhpParser\Node\Expr\BinaryOp\Identical; use PhpParser\Node\Expr\BinaryOp\NotIdentical; +use PhpParser\Node\Expr\BooleanNot; use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\UnaryMinus; use Rector\Core\Rector\AbstractRector; @@ -39,6 +40,8 @@ class SomeClass public function run() { $isMatch = substr($haystack, -strlen($needle)) === $needle; + + $isNotMatch = substr($haystack, -strlen($needle)) !== $needle; } } CODE_SAMPLE @@ -49,6 +52,8 @@ class SomeClass public function run() { $isMatch = str_ends_with($haystack, $needle); + + $isNotMatch = !str_ends_with($haystack, $needle); } } CODE_SAMPLE @@ -76,7 +81,7 @@ CODE_SAMPLE * Covers: * $isMatch = substr($haystack, -strlen($needle)) === $needle; */ - private function refactorSubstr(BinaryOp $binaryOp): ?FuncCall + private function refactorSubstr(BinaryOp $binaryOp): FuncCall | BooleanNot | null { if ($binaryOp->left instanceof FuncCall && $this->isName($binaryOp->left, 'substr')) { $substrFuncCall = $binaryOp->left; @@ -95,7 +100,13 @@ CODE_SAMPLE return null; } - return $this->nodeFactory->createFuncCall('str_ends_with', [$haystack, $needle]); + $endsWithNode = $this->nodeFactory->createFuncCall('str_ends_with', [$haystack, $needle]); + + if ($binaryOp instanceof NotIdentical) { + return new BooleanNot($endsWithNode); + } + + return $endsWithNode; } private function refactorSubstrCompare(BinaryOp $binaryOp): ?FuncCall