rector/docs/auto_import_names.md
Tomas Votruba 4b9139b523 Updated Rector to commit b8d06063052510644cd2224cdf468aa2181e78dd
b8d0606305 [Doc] Typo fix; autoimportNames -> importNames (#2086)
2022-04-17 06:12:37 +00:00

1.8 KiB

Auto Import Names

Rector works with all class names as fully qualified by default, so it knows the exact types. In most coding standard, that's not desired behavior, because short version with use statement is preferred:

+use App\Some\Namespace\SomeClass;

-/** @var \App\Some\Namespace\SomeClass $object */
+/** @var SomeClass $object */

-$object = new \App\Some\Namespace\SomeClass();
+$object = new SomeClass();

To import FQN like these, configure rector.php with:

$rectorConfig->importNames();

Single short classes are imported too:

+use DateTime;
-$someClass = \DateTime();
+$someClass = DateTime();

Do you want to keep those?

$parameters->set(Option::IMPORT_SHORT_CLASSES, false);

If 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.

$parameters->set(Option::APPLY_AUTO_IMPORT_NAMES_ON_CHANGED_FILES_ONLY, true);

How to Remove Unused Imports?

To remove imports, use ECS with NoUnusedImportsFixer rule:

// ecs.php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use PhpCsFixer\Fixer\Import\NoUnusedImportsFixer;

return static function (ContainerConfigurator $containerConfigurator): void {
    $services = $containerConfigurator->services();
    $services->set(NoUnusedImportsFixer::class);
};

Run it:

vendor/bin/ecs check src --fix

Happy coding!