diff --git a/config/level/code-quality/code-quality.yml b/config/level/code-quality/code-quality.yml index 20373ff020a..24336973093 100644 --- a/config/level/code-quality/code-quality.yml +++ b/config/level/code-quality/code-quality.yml @@ -20,3 +20,4 @@ services: Rector\Php\Rector\FuncCall\RemoveExtraParametersRector: ~ Rector\CodeQuality\Rector\LogicalOr\LogicalOrToBooleanOrRector: ~ Rector\CodeQuality\Rector\BinaryOp\SimplifyDeMorganBinaryRector: ~ + Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector: ~ diff --git a/packages/CodeQuality/src/Rector/Ternary/SimplifyTautologyTernaryRector.php b/packages/CodeQuality/src/Rector/Ternary/SimplifyTautologyTernaryRector.php new file mode 100644 index 00000000000..6c0c4ec27f0 --- /dev/null +++ b/packages/CodeQuality/src/Rector/Ternary/SimplifyTautologyTernaryRector.php @@ -0,0 +1,69 @@ +binaryOpMaintainer = $binaryOpMaintainer; + } + + public function getDefinition(): RectorDefinition + { + return new RectorDefinition('Simplify tautology ternary to value', [ + new CodeSample( + '$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;', + '$value = $fullyQualifiedTypeHint;' + ), + ]); + } + + /** + * @return string[] + */ + public function getNodeTypes(): array + { + return [Ternary::class]; + } + + /** + * @param Ternary $node + */ + public function refactor(Node $node): ?Node + { + if (! $node->cond instanceof NotIdentical && ! $node->cond instanceof Identical) { + return null; + } + + $isMatch = $this->binaryOpMaintainer->matchFirstAndSecondConditionNode( + $node->cond, + function (Node $leftNode) use ($node) { + return $this->areNodesEqual($leftNode, $node->if); + }, + function (Node $leftNode) use ($node) { + return $this->areNodesEqual($leftNode, $node->else); + } + ); + + if ($isMatch === null) { + return null; + } + + return $node->if; + } +} diff --git a/packages/CodeQuality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/Fixture/fixture.php.inc b/packages/CodeQuality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/Fixture/fixture.php.inc new file mode 100644 index 00000000000..5e0474b6be0 --- /dev/null +++ b/packages/CodeQuality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/Fixture/fixture.php.inc @@ -0,0 +1,37 @@ + +----- + diff --git a/packages/CodeQuality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/SimplifyTautologyTernaryRectorTest.php b/packages/CodeQuality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/SimplifyTautologyTernaryRectorTest.php new file mode 100644 index 00000000000..53506e83697 --- /dev/null +++ b/packages/CodeQuality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/SimplifyTautologyTernaryRectorTest.php @@ -0,0 +1,19 @@ +doTestFiles([__DIR__ . '/Fixture/fixture.php.inc']); + } + + protected function getRectorClass(): string + { + return SimplifyTautologyTernaryRector::class; + } +}