Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rector how to avoid formatting source code?

Tags:

php

rector

When running a simple Rector rule NormalizeNamespaceByPSR4ComposerAutoloadFileSystemRector the source code will be completely formatted, line breaks and spaces that are used to beautify the source code are removed. How can this be avoided in Rector?

$services->set(NormalizeNamespaceByPSR4ComposerAutoloadFileSystemRector::class);

... is the only service config in rector.php.

Rector says "! [NOTE] File ..." will be added:" So according to the rule it creates a new file (actually it is the same file...). I susspect this looks new for Rector because of the added namespace by the rule.

like image 661
powtac Avatar asked May 04 '26 08:05

powtac


1 Answers

Rector doesn't have influence on that; the reformat happens because of how the PHP code parser works.

Rector uses PHP-Parser from nikic.
It generates a tree of tokens (AST - Abstract Syntax Tree) and will reassemble it, afterwards transformations.
Unfortunately the parser doesn't (iirc, it can't) keep track of white-spaces.

I'm not sure there's any way to prevent that or reconstitute the original spacing.
Try to follow the related GitHub issue.

like image 52
Kamafeather Avatar answered May 05 '26 20:05

Kamafeather