Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stefanzweifel/b8fc2e2551c6c35379f49535927870a9 to your computer and use it in GitHub Desktop.
Save stefanzweifel/b8fc2e2551c6c35379f49535927870a9 to your computer and use it in GitHub Desktop.
Rector Rule to enable ImmutableDates in Laravel by updating the AppServiceProvider
<?php
namespace App\Rector;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PHPStan\Type\ObjectType;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Illuminate\Support\Facades\Date;
use Carbon\CarbonImmutable;
use Illuminate\Support\ServiceProvider;
class UseCarbonImmutableInAppServiceProviderRector extends AbstractRector
{
/**
* @var string
*/
private const BOOT = 'boot';
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Add Date::use(CarbonImmutable::class) to boot method of AppServiceProvider', [
new CodeSample(<<<'CODE_SAMPLE'
public function boot()
{
//
}
CODE_SAMPLE, <<<'CODE_SAMPLE'
public function boot()
{
Date::use(CarbonImmutable::class)
}
CODE_SAMPLE
),
]);
}
/**
* @inheritDoc
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
* @return Node|null
*/
public function refactor(Node $node)
{
$classLike = $this->betterNodeFinder->findParentType($node, ClassLike::class);
if (! $classLike instanceof ClassLike) {
return null;
}
if (! $this->isObjectType($classLike, new ObjectType(ServiceProvider::class))) {
return null;
}
if (! $this->isName($classLike->name, 'AppServiceProvider')) {
return null;
}
if (! $this->isName($node->name, self::BOOT)) {
return null;
}
$fullyQualifiedDateFacade = new FullyQualified(Date::class);
$fullyQualifiedCarbonImmutable = new FullyQualified(CarbonImmutable::class);
$argument = new Node\Arg(new Node\Scalar\String_($fullyQualifiedCarbonImmutable));
$staticCall = new StaticCall($fullyQualifiedDateFacade, 'use', [$argument]);
$parentStaticCallExpression = new Expression($staticCall);
$node->stmts = array_merge([$parentStaticCallExpression], (array)$node->stmts);
return $node;
}
}
@stefanzweifel
Copy link
Author

This rule was created during a late night coding session to learn Rector. It's probably easier to do this manually by reading Michael's guide: https://dyrynda.com.au/blog/laravel-immutable-dates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment