I’m using the Rector ruleset UP_TO_PHP_74
to update a legacy application.
It mostly does a good job, but the problem I’m seeing a lot of is that it’s changing
...
use My/Namespace/My/Classname;
...
/** @var Guestlist */
private $myVariable;
… to this inline, fully qualified class name:
private /My/Namespace/My/Classname $myVariable;
This is something I do not want. (That’s why use
statements exist!)
Is there a way I can tell Rector to use use
statements instead of fully qualified inline references?
If not, is there a way I can tell Rector to run everything other than the rule that’s doing this?
Alternatively, is there a PHP CS Fixer rule that will automatically turn these inline references back into proper use statements?
2
Answers
Try adding this to rector config:
$rectorConfig->importNames();
(https://getrector.com/documentation/import-names)
For Auto Import Names:
rector provide
$rectorConfig->importNames();
For Single short classes:
$rectorConfig->importShortClasses(false);
based on your requirement you will be able to pass true/false in itIf you have set
Option::AUTO_IMPORT_NAMES
to true, rector is applying this to every analyzed file, even if no real change by a rector was applied to the file.The reason is that a so-called post-rector is responsible for this, namely the
NameImportingPostRector
.If you like to apply the Option::AUTO_IMPORT_NAMES only for real changed files, you can configure this.
To Remove unused Imports:
use the phpcs fixer for it
Another option is you can use the coding style:
rule
FullyQualifiedNameClassNameImportSkipVoter
It will prevent adding import statements if already there.