Skip to content

Commit

Permalink
[PHP 7.0] Add IfIssetToCoalescingRector (#3878)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed May 17, 2023
1 parent f2348ae commit a8fdf00
Show file tree
Hide file tree
Showing 6 changed files with 251 additions and 13 deletions.
45 changes: 32 additions & 13 deletions build/target-repository/docs/rector_rules_overview.md
@@ -1,4 +1,4 @@
# 403 Rules Overview
# 404 Rules Overview

<br>

Expand Down Expand Up @@ -34,7 +34,7 @@

- [Php56](#php56) (2)

- [Php70](#php70) (18)
- [Php70](#php70) (19)

- [Php71](#php71) (9)

Expand Down Expand Up @@ -4675,31 +4675,50 @@ Change typehint from `Exception` to `Throwable`.

<br>

### IfToSpaceshipRector
### IfIssetToCoalescingRector

Changes if/else to spaceship <=> where useful
Change if with isset and return to coalesce

- class: [`Rector\Php70\Rector\If_\IfToSpaceshipRector`](../rules/Php70/Rector/If_/IfToSpaceshipRector.php)
- class: [`Rector\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector`](../rules/Php70/Rector/StmtsAwareInterface/IfIssetToCoalescingRector.php)

```diff
class SomeClass
{
public function run()
private $items = [];

public function resolve($key)
{
usort($languages, function ($a, $b) {
- if ($a[0] === $b[0]) {
- return 0;
- }
- if (isset($this->items[$key])) {
- return $this->items[$key];
- }
-
- return ($a[0] < $b[0]) ? 1 : -1;
+ return $b[0] <=> $a[0];
});
- return 'fallback value';
+ return $this->items[$key] ?? 'fallback value';
}
}
```

<br>

### IfToSpaceshipRector

Changes if/else to spaceship <=> where useful

- class: [`Rector\Php70\Rector\If_\IfToSpaceshipRector`](../rules/Php70/Rector/If_/IfToSpaceshipRector.php)

```diff
usort($languages, function ($first, $second) {
-if ($first[0] === $second[0]) {
- return 0;
-}
-
-return ($first[0] < $second[0]) ? 1 : -1;
+return $second[0] <=> $first[0];
});
```

<br>

### ListSplitStringRector

`list()` cannot split string directly anymore, use `str_split()`
Expand Down
2 changes: 2 additions & 0 deletions config/set/php70.php
Expand Up @@ -17,6 +17,7 @@
use Rector\Php70\Rector\List_\EmptyListRector;
use Rector\Php70\Rector\MethodCall\ThisCallOnStaticMethodToStaticCallRector;
use Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector;
use Rector\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector;
use Rector\Php70\Rector\Switch_\ReduceMultipleDefaultSwitchRector;
use Rector\Php70\Rector\Ternary\TernaryToNullCoalescingRector;
use Rector\Php70\Rector\Ternary\TernaryToSpaceshipRector;
Expand All @@ -43,5 +44,6 @@
ThisCallOnStaticMethodToStaticCallRector::class,
BreakNotInLoopOrSwitchToReturnRector::class,
RenameMktimeWithoutArgsToTimeRector::class,
IfIssetToCoalescingRector::class,
]);
};
@@ -0,0 +1,35 @@
<?php

namespace Rector\Tests\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector\Fixture;

class SomeClass
{
private $items = [];

public function resolve($key)
{
if (isset($this->items[$key])) {
return $this->items[$key];
}

return 'fallback value';
}
}

?>
-----
<?php

namespace Rector\Tests\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector\Fixture;

class SomeClass
{
private $items = [];

public function resolve($key)
{
return $this->items[$key] ?? 'fallback value';
}
}

?>
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class IfIssetToCoalescingRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(IfIssetToCoalescingRector::class);
};
144 changes: 144 additions & 0 deletions rules/Php70/Rector/StmtsAwareInterface/IfIssetToCoalescingRector.php
@@ -0,0 +1,144 @@
<?php

declare(strict_types=1);

namespace Rector\Php70\Rector\StmtsAwareInterface;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\Expr\Isset_;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\Contract\PhpParser\Node\StmtsAwareInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector\IfIssetToCoalescingRectorTest
*/
final class IfIssetToCoalescingRector extends AbstractRector implements MinPhpVersionInterface
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change if with isset and return to coalesce', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
private $items = [];
public function resolve($key)
{
if (isset($this->items[$key])) {
return $this->items[$key];
}
return 'fallback value';
}
}
CODE_SAMPLE

,
<<<'CODE_SAMPLE'
class SomeClass
{
private $items = [];
public function resolve($key)
{
return $this->items[$key] ?? 'fallback value';
}
}
CODE_SAMPLE
),
]);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [StmtsAwareInterface::class];
}

/**
* @param StmtsAwareInterface $node
*/
public function refactor(Node $node): ?Node
{
if ($node->stmts === null) {
return null;
}

foreach ($node->stmts as $key => $stmt) {
if (! $stmt instanceof Return_) {
continue;
}

if (! $stmt->expr instanceof Expr) {
continue;
}

$previousStmt = $node->stmts[$key - 1] ?? null;

if (! $previousStmt instanceof If_) {
continue;
}

if (! $previousStmt->cond instanceof Isset_) {
continue;
}

$ifOnlyStmt = $this->matchBareIfOnlyStmt($previousStmt);

if (! $ifOnlyStmt instanceof Return_) {
continue;
}

if (! $ifOnlyStmt->expr instanceof Expr) {
continue;
}

$ifIsset = $previousStmt->cond;
if (! $this->nodeComparator->areNodesEqual($ifOnlyStmt->expr, $ifIsset->vars[0])) {
continue;
}

unset($node->stmts[$key - 1]);

$stmt->expr = new Coalesce($ifOnlyStmt->expr, $stmt->expr);
return $node;
}

return null;
}

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::NULL_COALESCE;
}

private function matchBareIfOnlyStmt(If_ $if): ?Stmt
{
if ($if->else instanceof Else_) {
return null;
}

if ($if->elseifs !== []) {
return null;
}

if (count($if->stmts) !== 1) {
return null;
}

return $if->stmts[0];
}
}

0 comments on commit a8fdf00

Please sign in to comment.