Repository navigation
Getting class or namespace error when creating custom rector using the nesbot/carbon library
#9924
|
Hi! Just created my first custom rector. It works! What I don't understand is the error I get from 2 out of 3 fixtures.
Fixture example: Error: Obviously, the file exists and has the |
Replies: 2 comments 2 replies
|
Could you sure the |
|
Sure! I'm aware that this approach is too simplistic, and it probably has room for improvement, but it works for our tests. Also, I have 3 "skip" fixtures that work well. # utils/rector/src/Rector/EnsureCarbonTestNowIsReleasedRector.php
namespace Utils\Rector\Rector;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Nop;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Rector\Rector\AbstractRector;
final class EnsureCarbonTestNowIsReleasedRector extends AbstractRector
{
public function __construct(
private readonly BetterNodeFinder $betterNodeFinder,
private readonly TestsNodeAnalyzer $testsNodeAnalyzer,
) {
}
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
if (null === $node->stmts || [] === $node->stmts) {
return null;
}
if (!str_starts_with($this->getName($node->name) ?? '', 'test')) {
return null;
}
if (!$this->testsNodeAnalyzer->isTestClassMethod($node)) {
return null;
}
/** @var StaticCall|null $lastStaticCall */
$lastStaticCall = null;
$staticCalls = $this->betterNodeFinder->findInstanceOf($node->stmts, StaticCall::class);
foreach ($staticCalls as $staticCall) {
if (
!$this->isName($staticCall->name, 'setTestNow') ||
!$this->isNames($staticCall->class, [Carbon::class, CarbonImmutable::class])
) {
continue;
}
$lastStaticCall = [] !== $staticCall->args ? $staticCall : null;
}
if (null === $lastStaticCall) {
return null;
}
$node->stmts[] = new Nop();
$node->stmts[] = new Expression(new StaticCall(clone $lastStaticCall->class, new Identifier('setTestNow')));
return $node;
}
} |
Could you sure the
EnsureCarbonTestNowIsReleasedRectorcode? Also, you probably have some autoload juggling issue, which usually resolved by register it https://getrector.com/documentation/static-reflection-and-autoload