Skip to content

Commit

Permalink
[Carbon] Add immutable support to other rules (#5896)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed May 19, 2024
1 parent 1fd156b commit fe31e19
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Rector\Tests\Carbon\Rector\MethodCall\DateTimeMethodCallToCarbonRector\Fixture;

final class Immutable
{
public function run()
{
$date = (new \DateTimeImmutable('today +20 day'))->format('Y-m-d');
}
}

?>
-----
<?php

namespace Rector\Tests\Carbon\Rector\MethodCall\DateTimeMethodCallToCarbonRector\Fixture;

final class Immutable
{
public function run()
{
$date = (\Carbon\CarbonImmutable::today()->addDays(20))->format('Y-m-d');
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function refactor(Node $node): ?Node
return null;
}

if (! $this->isName($new->class, 'DateTime')) {
if (! $this->isName($new->class, 'DateTime') && ! $this->isName($new->class, 'DateTimeImmutable')) {
return null;
}

Expand All @@ -93,7 +93,11 @@ public function refactor(Node $node): ?Node
return null;
}

$carbonFullyQualified = new FullyQualified('Carbon\Carbon');
if ($this->isName($new->class, 'DateTime')) {
$carbonFullyQualified = new FullyQualified('Carbon\Carbon');
} else {
$carbonFullyQualified = new FullyQualified('Carbon\CarbonImmutable');
}

$carbonCall = $this->carbonCallFactory->createFromDateTimeString($carbonFullyQualified, $firstArg->value);

Expand Down
10 changes: 5 additions & 5 deletions rules/Carbon/Rector/New_/DateTimeInstanceToCarbonRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

namespace Rector\Carbon\Rector\New_;

use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
Expand Down Expand Up @@ -57,6 +57,10 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): ?Node
{
if ($node->isFirstClassCallable()) {
return null;
}

if ($this->isName($node->class, 'DateTime')) {
return $this->refactorWithClass($node, 'Carbon\\Carbon');
}
Expand All @@ -70,10 +74,6 @@ public function refactor(Node $node): ?Node

public function refactorWithClass(New_ $new, string $className): MethodCall|StaticCall|null
{
if ($new->isFirstClassCallable()) {
return null;
}

// no arg? ::now()
$carbonFullyQualified = new FullyQualified($className);

Expand Down

0 comments on commit fe31e19

Please sign in to comment.