diff --git a/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/CoalesceToTernaryRectorTest.php b/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/CoalesceToTernaryRectorTest.php new file mode 100644 index 00000000000..794029d9f2d --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/CoalesceToTernaryRectorTest.php @@ -0,0 +1,28 @@ +doTestFile($filePath); + } + + public static function provideData(): Iterator + { + return self::yieldFilesFromDirectory(__DIR__ . '/Fixture'); + } + + public function provideConfigFilePath(): string + { + return __DIR__ . '/config/configured_rule.php'; + } +} diff --git a/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/Fixture/non_nullable_left.php.inc b/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/Fixture/non_nullable_left.php.inc new file mode 100644 index 00000000000..5c094d481ec --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/Fixture/non_nullable_left.php.inc @@ -0,0 +1,27 @@ + +----- + diff --git a/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/Fixture/skip_array_dim_fetch.php.inc b/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/Fixture/skip_array_dim_fetch.php.inc new file mode 100644 index 00000000000..0eb5a0df2f0 --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector/Fixture/skip_array_dim_fetch.php.inc @@ -0,0 +1,11 @@ +withRules([CoalesceToTernaryRector::class]); diff --git a/rules/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector.php b/rules/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector.php new file mode 100644 index 00000000000..e582396dcbb --- /dev/null +++ b/rules/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector.php @@ -0,0 +1,97 @@ +> + */ + public function getNodeTypes(): array + { + return [Coalesce::class]; + } + + /** + * @param Coalesce $node + */ + public function refactor(Node $node): ?Node + { + /** + * indexed data maybe false positive + */ + if ($node->left instanceof ArrayDimFetch) { + return null; + } + + /** + * Scope needs to use parent Coalesce to properly get type from left side of coalesce + */ + $scope = ScopeFetcher::fetch($node); + $nativeType = $scope->getNativeType($node->left); + + if ($nativeType instanceof ErrorType) { + return null; + } + + if ($nativeType instanceof MixedType) { + return null; + } + + if ($nativeType instanceof NullType) { + return null; + } + + if ($nativeType instanceof UnionType) { + foreach ($nativeType->getTypes() as $unionedType) { + if ($unionedType instanceof NullType) { + return null; + } + } + } + + return new Ternary($node->left, null, $node->right); + } +}