Skip to content

Commit

Permalink
Convert DateTimeImmutable to CarbonImmutable (#5895)
Browse files Browse the repository at this point in the history
* Convert DateTimeImmutable to CarbonImmutable

* add test fixture

* [ci-review] Rector Rectify

---------

Co-authored-by: Bastien Miclo <kylekatarnls@protonmail.com>
Co-authored-by: GitHub Action <actions@github.com>
  • Loading branch information
3 people committed May 19, 2024
1 parent b2ec1f0 commit 1fd156b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Rector\Tests\Carbon\Rector\New_\DateTimeInstanceToCarbonRector\Fixture;

final class IncludeDateTimeImmutable
{
public function run()
{
$date = new \DateTimeImmutable('now');
}
}

?>
-----
<?php

namespace Rector\Tests\Carbon\Rector\New_\DateTimeInstanceToCarbonRector\Fixture;

final class IncludeDateTimeImmutable
{
public function run()
{
$date = \Carbon\CarbonImmutable::now();
}
}

?>
25 changes: 18 additions & 7 deletions rules/Carbon/Rector/New_/DateTimeInstanceToCarbonRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 1fd156b

Please sign in to comment.