add few fixtures (#2279)

This commit is contained in:
Tomas Votruba 2022-05-10 19:25:25 +03:00 committed by GitHub
parent fa073d4408
commit 27476c0909
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 51 additions and 20 deletions

View File

@ -1341,7 +1341,7 @@ Changes compared to value and return of expr to direct return
```diff
$value = 'something';
-if ($value === 52) {
- return $value;
- return 52;
-}
-
return $value;

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\Tests\CodeQuality\Rector\If_\SimplifyIfExactValueReturnValueRector\Fixture;
final class SkipDifferentValue
{
public function run($value)
{
if ($value === 94) {
return 93;
}
return $value;
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\Tests\CodeQuality\Rector\If_\SimplifyIfExactValueReturnValueRector\Fixture;
final class SkipNotIdentical
{
public function run($value)
{
if ($value !== 93) {
return 93;
}
return $value;
}
}

View File

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Rector\CodeQuality\Rector\If_;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\NodeManipulator\IfManipulator;
@ -32,7 +33,7 @@ final class SimplifyIfExactValueReturnValueRector extends AbstractRector
<<<'CODE_SAMPLE'
$value = 'something';
if ($value === 52) {
return $value;
return 52;
}
return $value;
@ -60,21 +61,21 @@ CODE_SAMPLE
*/
public function refactor(Node $node): ?Return_
{
$comparedNode = $this->ifManipulator->matchIfValueReturnValue($node);
if ($comparedNode !== null) {
$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
if (! $nextNode instanceof Return_) {
return null;
}
if (! $this->nodeComparator->areNodesEqual($comparedNode, $nextNode->expr)) {
return null;
}
$this->removeNode($nextNode);
return clone $nextNode;
$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
if (! $nextNode instanceof Return_) {
return null;
}
return null;
$comparedNode = $this->ifManipulator->matchIfValueReturnValue($node);
if (! $comparedNode instanceof Expr) {
return null;
}
if (! $this->nodeComparator->areNodesEqual($comparedNode, $nextNode->expr)) {
return null;
}
$this->removeNode($nextNode);
return clone $nextNode;
}
}

View File

@ -79,8 +79,8 @@ final class IfManipulator
return null;
}
$insideIfNode = $stmts[0];
if (! $insideIfNode instanceof Return_) {
$insideIfStmt = $stmts[0];
if (! $insideIfStmt instanceof Return_) {
return null;
}
@ -88,11 +88,11 @@ final class IfManipulator
return null;
}
if ($this->nodeComparator->areNodesEqual($if->cond->left, $insideIfNode->expr)) {
if ($this->nodeComparator->areNodesEqual($if->cond->left, $insideIfStmt->expr)) {
return $if->cond->right;
}
if ($this->nodeComparator->areNodesEqual($if->cond->right, $insideIfNode->expr)) {
if ($this->nodeComparator->areNodesEqual($if->cond->right, $insideIfStmt->expr)) {
return $if->cond->left;
}