Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\Fixture;

class SkipBreak
{
public function run(int $int): string
{
$str = 'error';
switch (true) {
case $int === 0:
$str = 'zero';
break;
default:
$str = 'other';
break;
}

return $str;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\Fixture;

class SkipDefaultNotLast
{
public function run($value)
{
switch (true) {
default:
return 'maybe';
case $value === 0:
return 'no';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\Fixture;

class SkipFalse
{
public function run($value)
{
switch (false) {
case $value === 0:
return 'no';
default:
return 'maybe';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\Fixture;

class SkipNoDefault
{
public function run($value)
{
switch (true) {
case $value === 0:
return 'no';
case $value === 1:
return 'yes';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\Fixture;

class WithDefault
{
public function run($value)
{
switch (true) {
case $value === 0:
return 'no';
case $value === 1:
return 'yes';
case $value === 2:
return 'maybe';
default:
return 'nevermind';
}
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\Fixture;

class WithDefault
{
public function run($value)
{
return match (true) {
$value === 0 => 'no',
$value === 1 => 'yes',
$value === 2 => 'maybe',
default => 'nevermind',
};
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector;

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

final class SwitchTrueToMatchRectorTest 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';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector;
use Rector\Config\RectorConfig;
use Rector\ValueObject\PhpVersion;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->phpVersion(PhpVersion::PHP_80);
$rectorConfig->rule(SwitchTrueToMatchRector::class);
};
138 changes: 138 additions & 0 deletions rules/CodeQuality/Rector/Switch_/SwitchTrueToMatchRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php

declare(strict_types=1);

namespace Rector\CodeQuality\Rector\Switch_;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\MatchArm;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector\SwitchTrueToMatchRectorTest
*/
final class SwitchTrueToMatchRector extends AbstractRector implements MinPhpVersionInterface
{
public function __construct(
private readonly ValueResolver $valueResolver,
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change `switch (true)` of returning cases to `match (true)` expression', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run($value)
{
switch (true) {
case $value === 0:
return 'no';
case $value === 1:
return 'yes';
default:
return 'maybe';
}
}
}
CODE_SAMPLE

,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run($value)
{
return match (true) {
$value === 0 => 'no',
$value === 1 => 'yes',
default => 'maybe',
};
}
}
CODE_SAMPLE
),
]);
}

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

/**
* @param Switch_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->valueResolver->isTrue($node->cond)) {
return null;
}

if ($node->cases === []) {
return null;
}

$matchArms = [];
$hasDefault = false;

$lastCaseKey = array_key_last($node->cases);

foreach ($node->cases as $key => $case) {
// a match arm can only carry a single return expression
if (count($case->stmts) !== 1) {
return null;
}

$onlyStmt = $case->stmts[0];
if (! $onlyStmt instanceof Return_) {
return null;
}

if (! $onlyStmt->expr instanceof Expr) {
return null;
}

if ($case->cond instanceof Expr) {
$matchArms[] = new MatchArm([$case->cond], $onlyStmt->expr);
continue;
}

// default case must be the last one, as a match default arm catches everything
if ($key !== $lastCaseKey) {
return null;
}

$hasDefault = true;
$matchArms[] = new MatchArm(null, $onlyStmt->expr);
}

// require a default arm, otherwise match (true) throws UnhandledMatchError where switch (true) falls through
if (! $hasDefault) {
return null;
}

$match = new Match_($this->nodeFactory->createTrue(), $matchArms);

return new Return_($match);
}

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::MATCH_EXPRESSION;
}
}
2 changes: 2 additions & 0 deletions src/Config/Level/CodeQualityLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
use Rector\CodeQuality\Rector\Property\FixClassCaseSensitivityVarDocblockRector;
use Rector\CodeQuality\Rector\StmtsAwareInterface\MoveInnerFunctionToTopLevelRector;
use Rector\CodeQuality\Rector\Switch_\SingularSwitchToIfRector;
use Rector\CodeQuality\Rector\Switch_\SwitchTrueToMatchRector;
use Rector\CodeQuality\Rector\Ternary\ArrayKeyExistsTernaryThenValueToCoalescingRector;
use Rector\CodeQuality\Rector\Ternary\NumberCompareToMaxFuncCallRector;
use Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector;
Expand Down Expand Up @@ -170,6 +171,7 @@ final class CodeQualityLevel
VariableConstFetchToClassConstFetchRector::class,
SwitchNegatedTernaryRector::class,
SingularSwitchToIfRector::class,
SwitchTrueToMatchRector::class,
SimplifyIfNullableReturnRector::class,
CallUserFuncWithArrowFunctionToInlineRector::class,
FlipTypeControlToUseExclusiveTypeRector::class,
Expand Down
Loading