diff --git a/rules-tests/Carbon/Rector/New_/DateTimeInstanceToCarbonRector/Fixture/include_datetime_immutable.php.inc b/rules-tests/Carbon/Rector/New_/DateTimeInstanceToCarbonRector/Fixture/include_datetime_immutable.php.inc new file mode 100644 index 00000000000..4aa5fa52884 --- /dev/null +++ b/rules-tests/Carbon/Rector/New_/DateTimeInstanceToCarbonRector/Fixture/include_datetime_immutable.php.inc @@ -0,0 +1,27 @@ + +----- + diff --git a/rules/Carbon/Rector/New_/DateTimeInstanceToCarbonRector.php b/rules/Carbon/Rector/New_/DateTimeInstanceToCarbonRector.php index c7ba81cc734..28c71e8d5a3 100644 --- a/rules/Carbon/Rector/New_/DateTimeInstanceToCarbonRector.php +++ b/rules/Carbon/Rector/New_/DateTimeInstanceToCarbonRector.php @@ -4,6 +4,7 @@ namespace Rector\Carbon\Rector\New_; +use PhpParser\Node\Expr\MethodCall; use PhpParser\Node; use PhpParser\Node\Expr\New_; use PhpParser\Node\Expr\StaticCall; @@ -56,22 +57,32 @@ public function getNodeTypes(): array */ public function refactor(Node $node): ?Node { - if (! $this->isName($node->class, 'DateTime')) { - return null; + if ($this->isName($node->class, 'DateTime')) { + return $this->refactorWithClass($node, 'Carbon\\Carbon'); + } + + if ($this->isName($node->class, 'DateTimeImmutable')) { + return $this->refactorWithClass($node, 'Carbon\\CarbonImmutable'); } - if ($node->isFirstClassCallable()) { + return null; + } + + public function refactorWithClass(New_ $new, string $className): MethodCall|StaticCall|null + { + if ($new->isFirstClassCallable()) { return null; } // no arg? ::now() - $carbonFullyQualified = new FullyQualified('Carbon\Carbon'); - if ($node->args === []) { + $carbonFullyQualified = new FullyQualified($className); + + if ($new->args === []) { return new StaticCall($carbonFullyQualified, new Identifier('now')); } - if (count($node->getArgs()) === 1) { - $firstArg = $node->getArgs()[0]; + if (count($new->getArgs()) === 1) { + $firstArg = $new->getArgs()[0]; if ($firstArg->value instanceof String_) { return $this->carbonCallFactory->createFromDateTimeString($carbonFullyQualified, $firstArg->value);