From d8d7ee3ae8ba8b961bb24cca0d0355d4ce9e5a92 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Mon, 23 Nov 2026 22:27:52 +0100 Subject: [PATCH] Type hint RectorStyle instead of SymfonyStyle in services Split out of #8787. Services depend on RectorStyle, registered in the container; SymfonyStyle stays bound to the same instance for extensions. --- src/Application/ApplicationFileProcessor.php | 14 ++++----- src/Application/FileProcessor.php | 6 ++-- .../Output/ConsoleOutputFormatter.php | 30 +++++++++---------- src/Configuration/ConfigInitializer.php | 16 +++++----- src/Configuration/ConfigurationFactory.php | 8 ++--- src/Console/Command/ComposerBasedCommand.php | 16 +++++----- src/Console/Command/ListRulesCommand.php | 16 +++++----- src/Console/Command/ProcessCommand.php | 18 +++++------ src/Console/Command/ValidateConfigCommand.php | 14 ++++----- src/Console/ConsoleApplication.php | 6 ++-- .../LazyContainerFactory.php | 11 +++++-- src/Reporting/DeprecatedRulesReporter.php | 14 ++++----- src/Reporting/MissConfigurationReporter.php | 22 +++++++------- src/Util/NodePrinter.php | 8 ++--- .../Command/ComposerBasedCommandTest.php | 9 ++++-- .../Command/ValidateConfigCommandTest.php | 13 ++++---- .../MissConfigurationReporterTest.php | 9 ++++-- 17 files changed, 123 insertions(+), 107 deletions(-) diff --git a/src/Application/ApplicationFileProcessor.php b/src/Application/ApplicationFileProcessor.php index 9467568f523..42877400060 100644 --- a/src/Application/ApplicationFileProcessor.php +++ b/src/Application/ApplicationFileProcessor.php @@ -10,6 +10,7 @@ use Rector\Caching\Detector\ChangedFilesDetector; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\Style\RectorStyle; use Rector\FileSystem\FilesFinder; use Rector\Parallel\Application\ParallelFileProcessor; use Rector\Parallel\CpuCoreCountProvider; @@ -27,7 +28,6 @@ use Rector\ValueObject\ProcessResult; use Rector\ValueObject\Reporting\FileDiff; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; final class ApplicationFileProcessor @@ -40,7 +40,7 @@ final class ApplicationFileProcessor private array $systemErrors = []; public function __construct( - private readonly SymfonyStyle $symfonyStyle, + private readonly RectorStyle $rectorStyle, private readonly FilesFinder $filesFinder, private readonly ParallelFileProcessor $parallelFileProcessor, private readonly ScheduleFactory $scheduleFactory, @@ -76,11 +76,11 @@ public function run(Configuration $configuration, InputInterface $input): Proces */ if ($configuration->shouldShowProgressBar()) { $fileCount = count($filePaths); - $this->symfonyStyle->progressStart($fileCount); - $this->symfonyStyle->progressAdvance(0); + $this->rectorStyle->progressStart($fileCount); + $this->rectorStyle->progressAdvance(0); $postFileCallback = function (int $stepCount): void { - $this->symfonyStyle->progressAdvance($stepCount); + $this->rectorStyle->progressAdvance($stepCount); // running in parallel here → nothing else to do }; } else { @@ -90,7 +90,7 @@ public function run(Configuration $configuration, InputInterface $input): Proces if ($configuration->isDebug()) { $preFileCallback = function (string $filePath): void { - $this->symfonyStyle->writeln('[file] ' . $filePath); + $this->rectorStyle->writeln('[file] ' . $filePath); }; } else { $preFileCallback = null; @@ -212,7 +212,7 @@ private function resolveSystemError(Throwable $throwable, string $filePath): Sys { $errorMessage = sprintf('System error: "%s"', $throwable->getMessage()) . PHP_EOL; - if ($this->symfonyStyle->isDebug()) { + if ($this->rectorStyle->isDebug()) { $errorMessage .= PHP_EOL . 'Stack trace:' . PHP_EOL . $throwable->getTraceAsString(); } else { $errorMessage .= 'Run Rector with "--debug" option and post the report here: https://github.com/rectorphp/rector/issues/new'; diff --git a/src/Application/FileProcessor.php b/src/Application/FileProcessor.php index 7043b8af2f5..b628792dfa7 100644 --- a/src/Application/FileProcessor.php +++ b/src/Application/FileProcessor.php @@ -13,6 +13,7 @@ use Rector\ChangesReporting\ValueObjectFactory\ErrorFactory; use Rector\ChangesReporting\ValueObjectFactory\FileDiffFactory; use Rector\CodingStyle\ClassNameImport\UsedImportsResolver; +use Rector\Console\Style\RectorStyle; use Rector\Exception\ShouldNotHappenException; use Rector\FileSystem\FilePathHelper; use Rector\NodeTypeResolver\NodeScopeAndMetadataDecorator; @@ -27,7 +28,6 @@ use Rector\ValueObject\Configuration; use Rector\ValueObject\Error\SystemError; use Rector\ValueObject\FileProcessResult; -use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; final readonly class FileProcessor @@ -35,7 +35,7 @@ public function __construct( private BetterStandardPrinter $betterStandardPrinter, private RectorNodeTraverser $rectorNodeTraverser, - private SymfonyStyle $symfonyStyle, + private RectorStyle $rectorStyle, private FileDiffFactory $fileDiffFactory, private ChangedFilesDetector $changedFilesDetector, private ErrorFactory $errorFactory, @@ -151,7 +151,7 @@ private function parseFileAndDecorateNodes(File $file): ?SystemError return $this->errorFactory->createAutoloadError($analysedCodeException, $file->getFilePath()); } catch (Throwable $throwable) { - if ($this->symfonyStyle->isVerbose() || StaticPHPUnitEnvironment::isPHPUnitRun()) { + if ($this->rectorStyle->isVerbose() || StaticPHPUnitEnvironment::isPHPUnitRun()) { throw $throwable; } diff --git a/src/ChangesReporting/Output/ConsoleOutputFormatter.php b/src/ChangesReporting/Output/ConsoleOutputFormatter.php index afd48e240d0..796b7600cd7 100644 --- a/src/ChangesReporting/Output/ConsoleOutputFormatter.php +++ b/src/ChangesReporting/Output/ConsoleOutputFormatter.php @@ -8,12 +8,12 @@ use Rector\ChangesReporting\Contract\Output\OutputFormatterInterface; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\Style\RectorStyle; use Rector\ValueObject\Configuration; use Rector\ValueObject\Error\SystemError; use Rector\ValueObject\ProcessResult; use Rector\ValueObject\Reporting\FileDiff; use Symfony\Component\Console\Formatter\OutputFormatter; -use Symfony\Component\Console\Style\SymfonyStyle; final readonly class ConsoleOutputFormatter implements OutputFormatterInterface { @@ -25,7 +25,7 @@ private const string ON_LINE_REGEX = '# on line #'; public function __construct( - private SymfonyStyle $symfonyStyle, + private RectorStyle $rectorStyle, ) { } @@ -43,7 +43,7 @@ public function report(ProcessResult $processResult, Configuration $configuratio // to keep space between progress bar and success message if ($configuration->shouldShowProgressBar() && $processResult->getFileDiffs() === []) { - $this->symfonyStyle->newLine(); + $this->rectorStyle->newLine(); } if ($configuration->shouldShowRulesSummary()) { @@ -51,7 +51,7 @@ public function report(ProcessResult $processResult, Configuration $configuratio } $message = $this->createSuccessMessage($processResult, $configuration); - $this->symfonyStyle->success($message); + $this->rectorStyle->success($message); } public function getName(): string @@ -72,7 +72,7 @@ private function reportFileDiffs(array $fileDiffs, bool $absoluteFilePath): void ksort($fileDiffs); $message = sprintf('%d file%s with changes', count($fileDiffs), count($fileDiffs) === 1 ? '' : 's'); - $this->symfonyStyle->title($message); + $this->rectorStyle->title($message); $i = 0; foreach ($fileDiffs as $fileDiff) { @@ -95,14 +95,14 @@ private function reportFileDiffs(array $fileDiffs, bool $absoluteFilePath): void $message = sprintf('%d) %s', ++$i, $filePathWithUrl); - $this->symfonyStyle->writeln($message); - $this->symfonyStyle->newLine(); - $this->symfonyStyle->writeln($fileDiff->getDiffConsoleFormatted()); + $this->rectorStyle->writeln($message); + $this->rectorStyle->newLine(); + $this->rectorStyle->writeln($fileDiff->getDiffConsoleFormatted()); if ($fileDiff->getRectorChanges() !== []) { - $this->symfonyStyle->writeln('Applied rules:'); - $this->symfonyStyle->listing($fileDiff->getRectorShortClasses()); - $this->symfonyStyle->newLine(); + $this->rectorStyle->writeln('Applied rules:'); + $this->rectorStyle->listing($fileDiff->getRectorShortClasses()); + $this->rectorStyle->newLine(); } } } @@ -131,7 +131,7 @@ private function reportErrors(array $errors, bool $absoluteFilePath): void $message .= ' On line: ' . $error->getLine(); } - $this->symfonyStyle->error($message); + $this->rectorStyle->error($message); } } @@ -144,11 +144,11 @@ private function reportRulesSummary(ProcessResult $processResult, Configuration $verb = $configuration->isDryRun() ? 'would have been applied' : 'was applied'; - $this->symfonyStyle->section('Rules Summary'); + $this->rectorStyle->section('Rules Summary'); foreach ($ruleApplicationCounts as $ruleClass => $count) { $ruleShortClass = (string) Strings::after($ruleClass, '\\', -1); - $this->symfonyStyle->writeln(sprintf( + $this->rectorStyle->writeln(sprintf( ' * %s %s %d time%s', $ruleShortClass, $verb, @@ -157,7 +157,7 @@ private function reportRulesSummary(ProcessResult $processResult, Configuration )); } - $this->symfonyStyle->newLine(); + $this->rectorStyle->newLine(); } private function normalizePathsToRelativeWithLine(string $errorMessage): string diff --git a/src/Configuration/ConfigInitializer.php b/src/Configuration/ConfigInitializer.php index 8cb5e634b5e..a52283a1ca7 100644 --- a/src/Configuration/ConfigInitializer.php +++ b/src/Configuration/ConfigInitializer.php @@ -7,10 +7,10 @@ use Nette\Utils\FileSystem; use Rector\Agentic\TerminalDetector; use Rector\Bootstrap\RectorConfigsResolver; +use Rector\Console\Style\RectorStyle; use Rector\Contract\Rector\RectorInterface; use Rector\FileSystem\InitFilePathsResolver; use Rector\PostRector\Contract\Rector\PostRectorInterface; -use Symfony\Component\Console\Style\SymfonyStyle; final readonly class ConfigInitializer { @@ -20,7 +20,7 @@ public function __construct( private array $rectors, private InitFilePathsResolver $initFilePathsResolver, - private SymfonyStyle $symfonyStyle, + private RectorStyle $rectorStyle, private RectorConfigsResolver $rectorConfigsResolver, ) { } @@ -31,14 +31,14 @@ public function createConfig(string $projectDirectory): void $distRectorConfigPath = $projectDirectory . '/' . RectorConfigsResolver::DEFAULT_DIST_CONFIG_FILE; if (file_exists($commonRectorConfigPath)) { - $this->symfonyStyle->warning( + $this->rectorStyle->warning( 'Register rules or sets in your "' . RectorConfigsResolver::DEFAULT_CONFIG_FILE . '" config' ); return; } if (file_exists($distRectorConfigPath)) { - $this->symfonyStyle->warning( + $this->rectorStyle->warning( 'Register rules or sets in your "' . RectorConfigsResolver::DEFAULT_DIST_CONFIG_FILE . '" config' ); return; @@ -47,7 +47,7 @@ public function createConfig(string $projectDirectory): void $mainConfigFile = $this->rectorConfigsResolver->provide() ->getMainConfigFile(); if ($mainConfigFile !== null && file_exists($mainConfigFile)) { - $this->symfonyStyle->warning( + $this->rectorStyle->warning( 'Register rules or sets in your "' . basename($mainConfigFile) . '" config' ); return; @@ -56,14 +56,14 @@ public function createConfig(string $projectDirectory): void // non-interactive terminal, e.g. piped output, CI or an agent: never prompt or silently write a // config, just say what to do - Symfony still treats a closed STDIN as interactive here if (! TerminalDetector::isInputTty()) { - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'No "%s" config found. Create one, or pass "--config ".', RectorConfigsResolver::DEFAULT_CONFIG_FILE )); return; } - $response = $this->symfonyStyle->ask( + $response = $this->rectorStyle->ask( 'No "' . RectorConfigsResolver::DEFAULT_CONFIG_FILE . '" config found. Should we generate it for you?', 'yes' ); @@ -77,7 +77,7 @@ public function createConfig(string $projectDirectory): void $configContents = $this->replacePathsContents($configContents, $projectDirectory); FileSystem::write($commonRectorConfigPath, $configContents, null); - $this->symfonyStyle->success('The config is added now. Re-run command to make Rector do the work!'); + $this->rectorStyle->success('The config is added now. Re-run command to make Rector do the work!'); } public function areSomeRectorsLoaded(): bool diff --git a/src/Configuration/ConfigurationFactory.php b/src/Configuration/ConfigurationFactory.php index e2bceff3ab1..5242b7b1574 100644 --- a/src/Configuration/ConfigurationFactory.php +++ b/src/Configuration/ConfigurationFactory.php @@ -7,10 +7,10 @@ use Rector\Agentic\TerminalDetector; use Rector\ChangesReporting\Output\ConsoleOutputFormatter; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\Style\RectorStyle; use Rector\FileSystem\FilePathFilter; use Rector\ValueObject\Configuration; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; use Webmozart\Assert\Assert; /** @@ -19,7 +19,7 @@ final readonly class ConfigurationFactory { public function __construct( - private SymfonyStyle $symfonyStyle, + private RectorStyle $rectorStyle, private OnlyRuleResolver $onlyRuleResolver, private FilePathFilter $filePathFilter, ) { @@ -76,7 +76,7 @@ public function createFromInput(InputInterface $input): Configuration $onlySuffix = $input->getOption(Option::ONLY_SUFFIX); if ($onlySuffix !== null) { - $this->symfonyStyle->warning( + $this->rectorStyle->warning( 'The "--only-suffix" option is deprecated and will be removed. Use "--filter" instead, e.g. --filter="*Controller.php"' ); } @@ -179,7 +179,7 @@ private function shouldShowProgressBar(InputInterface $input, string $outputForm return false; } - if ($this->symfonyStyle->isVerbose()) { + if ($this->rectorStyle->isVerbose()) { return false; } diff --git a/src/Console/Command/ComposerBasedCommand.php b/src/Console/Command/ComposerBasedCommand.php index 60be06c7729..9146ecce656 100644 --- a/src/Console/Command/ComposerBasedCommand.php +++ b/src/Console/Command/ComposerBasedCommand.php @@ -9,6 +9,7 @@ use Rector\Composer\InstalledPackageResolver; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\Style\RectorStyle; use Rector\Contract\Rector\RectorInterface; use Rector\VersionBonding\Contract\ComposerPackageConstraintInterface; use Rector\VersionBonding\ValueObject\ComposerBoundRuleConfiguration; @@ -18,7 +19,6 @@ use Symfony\Component\Console\Helper\TableSeparator; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; /** * @see \Rector\Tests\Console\Command\ComposerBasedCommandTest @@ -29,7 +29,7 @@ final class ComposerBasedCommand extends Command * @param RectorInterface[] $rectors */ public function __construct( - private readonly SymfonyStyle $symfonyStyle, + private readonly RectorStyle $rectorStyle, private readonly InstalledPackageResolver $installedPackageResolver, private readonly array $rectors ) { @@ -48,22 +48,22 @@ protected function execute(InputInterface $input, OutputInterface $output): int $configurationTableRows = $this->createConfigurationTableRows(); if ($tableRows === [] && $configurationTableRows === []) { - $this->symfonyStyle->warning('No composer package bound rule is loaded'); + $this->rectorStyle->warning('No composer package bound rule is loaded'); return Command::SUCCESS; } if ($tableRows !== []) { - $this->symfonyStyle->title('Composer package bound rules'); - $this->symfonyStyle->table(['Rule', 'Package', 'Requires', 'Installed', 'Active'], $tableRows); + $this->rectorStyle->title('Composer package bound rules'); + $this->rectorStyle->table(['Rule', 'Package', 'Requires', 'Installed', 'Active'], $tableRows); } if ($configurationTableRows !== []) { - $this->symfonyStyle->title('Composer package bound rule configuration'); + $this->rectorStyle->title('Composer package bound rule configuration'); $headers = ['Rule', 'Package', 'Requires', 'Installed', 'Active']; - $table = $this->symfonyStyle->createTable(); + $table = $this->rectorStyle->createTable(); $table->setHeaders($headers); $table->setRows($this->createConfigurationDisplayRows($configurationTableRows)); @@ -83,7 +83,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $allTableRows = [...$tableRows, ...$configurationTableRows]; $activeCount = count(array_filter($allTableRows, static fn (array $tableRow): bool => $tableRow[4] === 'yes')); - $this->symfonyStyle->note( + $this->rectorStyle->note( sprintf('%d of %d composer package bound items are active', $activeCount, count($allTableRows)) ); diff --git a/src/Console/Command/ListRulesCommand.php b/src/Console/Command/ListRulesCommand.php index 182660b20ca..05eddd3ed42 100644 --- a/src/Console/Command/ListRulesCommand.php +++ b/src/Console/Command/ListRulesCommand.php @@ -8,6 +8,7 @@ use Rector\ChangesReporting\Output\ConsoleOutputFormatter; use Rector\Configuration\Option; use Rector\Console\Rule\AllRectorRulesProvider; +use Rector\Console\Style\RectorStyle; use Rector\Contract\Rector\RectorInterface; use Rector\PostRector\Contract\Rector\PostRectorInterface; use Rector\Skipper\Skipper\Skipper; @@ -15,7 +16,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; final class ListRulesCommand extends Command { @@ -23,7 +23,7 @@ final class ListRulesCommand extends Command * @param RectorInterface[] $rectors */ public function __construct( - private readonly SymfonyStyle $symfonyStyle, + private readonly RectorStyle $rectorStyle, private readonly Skipper $skipper, private readonly AllRectorRulesProvider $allRectorRulesProvider, private readonly array $rectors @@ -75,16 +75,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::SUCCESS; } - $this->symfonyStyle->title('Loaded Rector rules'); - $this->symfonyStyle->listing($rectorClasses); + $this->rectorStyle->title('Loaded Rector rules'); + $this->rectorStyle->listing($rectorClasses); if ($skippedClasses !== []) { - $this->symfonyStyle->title('Skipped Rector rules'); - $this->symfonyStyle->listing($skippedClasses); + $this->rectorStyle->title('Skipped Rector rules'); + $this->rectorStyle->listing($skippedClasses); } - $this->symfonyStyle->newLine(); - $this->symfonyStyle->note(sprintf('Loaded %d rules', count($rectorClasses))); + $this->rectorStyle->newLine(); + $this->rectorStyle->note(sprintf('Loaded %d rules', count($rectorClasses))); return Command::SUCCESS; } diff --git a/src/Console/Command/ProcessCommand.php b/src/Console/Command/ProcessCommand.php index 023379c3d1f..d6563193ef1 100644 --- a/src/Console/Command/ProcessCommand.php +++ b/src/Console/Command/ProcessCommand.php @@ -15,6 +15,7 @@ use Rector\Console\ExitCode; use Rector\Console\Output\OutputFormatterCollector; use Rector\Console\ProcessConfigureDecorator; +use Rector\Console\Style\RectorStyle; use Rector\Exception\ShouldNotHappenException; use Rector\Reporting\DeprecatedRulesReporter; use Rector\Reporting\MissConfigurationReporter; @@ -28,7 +29,6 @@ use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; final class ProcessCommand extends Command { @@ -39,7 +39,7 @@ public function __construct( private readonly ApplicationFileProcessor $applicationFileProcessor, private readonly DynamicSourceLocatorDecorator $dynamicSourceLocatorDecorator, private readonly OutputFormatterCollector $outputFormatterCollector, - private readonly SymfonyStyle $symfonyStyle, + private readonly RectorStyle $rectorStyle, private readonly MemoryLimiter $memoryLimiter, private readonly ConfigurationFactory $configurationFactory, private readonly DeprecatedRulesReporter $deprecatedRulesReporter, @@ -95,12 +95,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int // disable console output in case of json output formatter if ($configuration->getOutputFormat() === JsonOutputFormatter::NAME) { - $this->symfonyStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET); + $this->rectorStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET); } // "--rules-summary" is a human-only table; the JSON format carries richer per-rule data if ($configuration->shouldShowRulesSummary()) { - $this->symfonyStyle->getErrorStyle() + $this->rectorStyle->getErrorStyle() ->warning( 'The "--rules-summary" option is deprecated and will be removed. Use "--output-format=json" instead, which reports every applied rule with its file and line.' ); @@ -117,7 +117,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int // 0. warn about skipped rules that are deprecated if ($this->skipper->resolveDeprecatedSkippedClasses() !== []) { - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'These rules are skipped, but are deprecated. Most likely you do not need to skip them anymore as not part of any set and remove them: %s%s', "\n\n", '* ' . implode("\n* ", $this->skipper->resolveDeprecatedSkippedClasses()) . "\n" @@ -127,7 +127,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int // 1. warn about rules registered in both withRules() and sets to avoid bloated rector.php configs $setAndRulesDuplicatedRegistrations = $configuration->getBothSetAndRulesDuplicatedRegistrations(); if ($setAndRulesDuplicatedRegistrations !== []) { - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'These rules are registered in both sets and "withRules()". Remove them from "withRules()" to avoid duplications: %s* %s', "\n\n", implode(' * ', $setAndRulesDuplicatedRegistrations) . "\n" @@ -139,7 +139,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($this->dynamicSourceLocatorDecorator->arePathsEmpty()) { // read from rector.php, no paths definition needs withPaths() config if ($paths === []) { - $this->symfonyStyle->error( + $this->rectorStyle->error( 'Provide paths in Rector config. See ways: https://getrector.com/documentation/define-paths' ); @@ -148,7 +148,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int // read from cli paths arguments, eg: vendor/bin/rector process A B C which A, B, and C not exists $isSingular = count($paths) === 1; - $this->symfonyStyle->error( + $this->rectorStyle->error( sprintf( 'The following given path%s do%s not match any file%s or director%s: %s%s', $isSingular ? '' : 's', @@ -247,7 +247,7 @@ private function reportLevelOverflow(LevelOverflow $levelOverflow): void $levelOverflow->getSuggestedRuleset() ) : sprintf('->withSets(SetList::%s)', $levelOverflow->getSuggestedSetListConstant()); - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'The "->%s()" level contains only %d rules, but you set level to %d.%sYou are using the full set now! Time to switch to more efficient "%s".', $levelOverflow->getConfigurationName(), $levelOverflow->getRuleCount(), diff --git a/src/Console/Command/ValidateConfigCommand.php b/src/Console/Command/ValidateConfigCommand.php index 164d414816f..3c2f953e911 100644 --- a/src/Console/Command/ValidateConfigCommand.php +++ b/src/Console/Command/ValidateConfigCommand.php @@ -9,6 +9,7 @@ use Rector\ChangesReporting\Output\JsonOutputFormatter; use Rector\Configuration\Option; use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyle; use Rector\Reporting\DeprecatedRulesReporter; use Rector\Reporting\MissConfigurationReporter; use Rector\Skipper\Skipper\Skipper; @@ -17,7 +18,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; /** * @see \Rector\Tests\Console\Command\ValidateConfigCommandTest @@ -25,7 +25,7 @@ final class ValidateConfigCommand extends Command { public function __construct( - private readonly SymfonyStyle $symfonyStyle, + private readonly RectorStyle $rectorStyle, private readonly DeprecatedRulesReporter $deprecatedRulesReporter, private readonly MissConfigurationReporter $missConfigurationReporter, private readonly Skipper $skipper, @@ -52,7 +52,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int // silence the human-readable warnings, so only the JSON payload lands on stdout if ($isJsonOutput) { - $this->symfonyStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET); + $this->rectorStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET); } $issueCount = 0; @@ -78,11 +78,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int } if ($issueCount === 0) { - $this->symfonyStyle->success('Config is valid, no issues found'); + $this->rectorStyle->success('Config is valid, no issues found'); return ExitCode::SUCCESS; } - $this->symfonyStyle->error(sprintf( + $this->rectorStyle->error(sprintf( '%d config %s found, see the warnings above', $issueCount, $issueCount === 1 ? 'issue' : 'issues' @@ -98,7 +98,7 @@ private function reportDeprecatedSkippedClasses(): int return 0; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'These rules are skipped, but are deprecated. Most likely you do not need to skip them anymore, remove them: %s%s', "\n\n", '* ' . implode("\n* ", $deprecatedSkippedClasses) . "\n" @@ -115,7 +115,7 @@ private function reportSetAndRulesDuplicatedRegistrations(): int return 0; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'These rules are registered in both sets and "withRules()". Remove them from "withRules()" to avoid duplications: %s* %s', "\n\n", implode(' * ', $setAndRulesDuplicatedRegistrations) . "\n" diff --git a/src/Console/ConsoleApplication.php b/src/Console/ConsoleApplication.php index 2fee6c57f73..1d09cec2277 100644 --- a/src/Console/ConsoleApplication.php +++ b/src/Console/ConsoleApplication.php @@ -7,6 +7,7 @@ use Rector\Application\VersionResolver; use Rector\ChangesReporting\Output\ConsoleOutputFormatter; use Rector\Configuration\Option; +use Rector\Console\Style\RectorStyle; use Rector\Util\Reflection\PrivatesAccessor; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; @@ -14,7 +15,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; use Webmozart\Assert\Assert; final class ConsoleApplication extends Application @@ -26,7 +26,7 @@ final class ConsoleApplication extends Application */ public function __construct( array $commands, - private readonly SymfonyStyle $symfonyStyle + private readonly RectorStyle $rectorStyle ) { parent::__construct(self::NAME, VersionResolver::PACKAGE_VERSION); @@ -83,7 +83,7 @@ public function doRun(InputInterface $input, OutputInterface $output): int $tokens = array_merge(['process'], $tokens); $privatesAccessor->setPrivateProperty($input, 'tokens', $tokens); } elseif (! $this->has($commandName)) { - $this->symfonyStyle->error( + $this->rectorStyle->error( sprintf( 'The following given path does not match any files or directories: %s%s', "\n\n - ", diff --git a/src/DependencyInjection/LazyContainerFactory.php b/src/DependencyInjection/LazyContainerFactory.php index e067b92e2db..0c9feaa1c9a 100644 --- a/src/DependencyInjection/LazyContainerFactory.php +++ b/src/DependencyInjection/LazyContainerFactory.php @@ -30,6 +30,7 @@ use Rector\Console\Command\WorkerCommand; use Rector\Console\ConsoleApplication; use Rector\Console\Rule\AllRectorRulesProvider; +use Rector\Console\Style\RectorStyle; use Rector\Console\Style\SymfonyStyleFactory; use Rector\Contract\PhpParser\DecoratingNodeVisitorInterface; use Rector\NodeNameResolver\NodeNameResolver; @@ -198,13 +199,19 @@ private function registerTaggedServices(RectorConfig $rectorConfig): void $rectorConfig->autodiscover(__DIR__ . '/../ChangesReporting/Output'); $rectorConfig->singleton( - SymfonyStyle::class, - static function (RectorConfig $rectorConfig): SymfonyStyle { + RectorStyle::class, + static function (RectorConfig $rectorConfig): RectorStyle { $symfonyStyleFactory = $rectorConfig->make(SymfonyStyleFactory::class); return $symfonyStyleFactory->create(); } ); + // kept for extensions that still inject SymfonyStyle + $rectorConfig->singleton( + SymfonyStyle::class, + static fn (RectorConfig $rectorConfig): SymfonyStyle => $rectorConfig->make(RectorStyle::class) + ); + } private function registerAnnotationToAttributeSetters(RectorConfig $rectorConfig): void diff --git a/src/Reporting/DeprecatedRulesReporter.php b/src/Reporting/DeprecatedRulesReporter.php index 054c995b603..3d558b08ed3 100644 --- a/src/Reporting/DeprecatedRulesReporter.php +++ b/src/Reporting/DeprecatedRulesReporter.php @@ -7,12 +7,12 @@ use Rector\Configuration\Deprecation\Contract\DeprecatedInterface; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; -use Symfony\Component\Console\Style\SymfonyStyle; +use Rector\Console\Style\RectorStyle; final readonly class DeprecatedRulesReporter { public function __construct( - private SymfonyStyle $symfonyStyle + private RectorStyle $rectorStyle ) { } @@ -27,7 +27,7 @@ public function reportDeprecatedRules(): int continue; } - $this->symfonyStyle->warning( + $this->rectorStyle->warning( sprintf( 'Registered rule "%s" is deprecated and will be removed. Upgrade your config to use another rule or remove it', $registeredRectorRule @@ -50,7 +50,7 @@ public function reportDeprecatedSkippedRules(): int continue; } - $this->symfonyStyle->warning(sprintf('Skipped rule "%s" is deprecated', $skippedRectorRule)); + $this->rectorStyle->warning(sprintf('Skipped rule "%s" is deprecated', $skippedRectorRule)); ++$reportedCount; } @@ -66,7 +66,7 @@ public function reportDeprecatedAttributesSetsArgs(): int $reportedCount = 0; foreach (array_unique($deprecatedAttributesSetsArgs) as $deprecatedAttributesSetsArg) { - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'The "->withAttributesSets(%s: true)" argument is deprecated and no longer applied. It is already included in the "symfony: true" argument, use it instead.', $deprecatedAttributesSetsArg )); @@ -85,7 +85,7 @@ public function reportDeprecatedComposerBasedArgs(): int $reportedCount = 0; foreach (array_unique($deprecatedComposerBasedArgs) as $deprecatedComposerBasedArg) { - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'The "->withComposerBased(%s: true)" argument is deprecated and no longer applied. It only added named args to 2 methods of a single package, register the rule directly if needed.', $deprecatedComposerBasedArg )); @@ -104,7 +104,7 @@ public function reportDeprecatedPreparedSetsArgs(): int $reportedCount = 0; foreach (array_unique($deprecatedPreparedSetsArgs) as $deprecatedPreparedSetsArg) { - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'The "->withPreparedSets(%s: true)" argument is deprecated and no longer applied. Its rules were moved to the "codeQuality" and "codingStyle" sets, use them instead.', $deprecatedPreparedSetsArg )); diff --git a/src/Reporting/MissConfigurationReporter.php b/src/Reporting/MissConfigurationReporter.php index a4cb810438c..272e4300a8d 100644 --- a/src/Reporting/MissConfigurationReporter.php +++ b/src/Reporting/MissConfigurationReporter.php @@ -7,10 +7,10 @@ use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; use Rector\Configuration\VendorMissAnalyseGuard; +use Rector\Console\Style\RectorStyle; use Rector\Contract\Rector\RectorInterface; use Rector\PostRector\Contract\Rector\PostRectorInterface; use Rector\ValueObject\ProcessResult; -use Symfony\Component\Console\Style\SymfonyStyle; /** * @see \Rector\Tests\Reporting\MissConfigurationReporterTest @@ -18,7 +18,7 @@ final readonly class MissConfigurationReporter { public function __construct( - private SymfonyStyle $symfonyStyle, + private RectorStyle $rectorStyle, private VendorMissAnalyseGuard $vendorMissAnalyseGuard, private UnusedSkipResolver $unusedSkipResolver, private NeededSkipVerifier $neededSkipVerifier, @@ -36,7 +36,7 @@ public function reportUnusedSkips(ProcessResult $processResult): void return; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( '%s never matched any element. You can remove %s from "->withSkip()"', count($unusedSkips) > 1 ? 'These skips are unused, they' : 'This skip is unused, it', count($unusedSkips) > 1 ? 'them' : 'it' @@ -45,7 +45,7 @@ public function reportUnusedSkips(ProcessResult $processResult): void // add a blank line between items, so grouped rule skips stay visually separated $spacedUnusedSkips = array_map(static fn (string $unusedSkip): string => $unusedSkip . "\n", $unusedSkips); - $this->symfonyStyle->listing($spacedUnusedSkips); + $this->rectorStyle->listing($spacedUnusedSkips); } /** @@ -60,7 +60,7 @@ public function reportUnnecessarySkips(ProcessResult $processResult): void return; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( '%s matched a file, but the rule would not have changed it. You can remove %s from "->withSkip()"', count($unnecessarySkips) > 1 ? 'These skips are unnecessary, they' : 'This skip is unnecessary, it', count($unnecessarySkips) > 1 ? 'them' : 'it' @@ -72,7 +72,7 @@ public function reportUnnecessarySkips(ProcessResult $processResult): void $unnecessarySkips ); - $this->symfonyStyle->listing($spacedUnnecessarySkips); + $this->rectorStyle->listing($spacedUnnecessarySkips); } public function reportSkippedNeverRegisteredRules(): int @@ -92,13 +92,13 @@ public function reportSkippedNeverRegisteredRules(): int return 0; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( '%s never registered. You can remove %s from "->withSkip()"', count($neverRegisteredSkippedRules) > 1 ? 'These skipped rules are' : 'This skipped rule is', count($neverRegisteredSkippedRules) > 1 ? 'them' : 'it' )); - $this->symfonyStyle->listing($neverRegisteredSkippedRules); + $this->rectorStyle->listing($neverRegisteredSkippedRules); return count($neverRegisteredSkippedRules); } @@ -113,7 +113,7 @@ public function reportSkippedNonRectorClasses(): int return 0; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( '%s "%s" %s not a Rector rule, so %s never be skipped. Only classes that implement "%s" can be used in "->withSkip()"', count($skippedNonRectorClasses) > 1 ? 'These skipped classes' : 'This skipped class', implode('", "', $skippedNonRectorClasses), @@ -134,7 +134,7 @@ public function reportVendorInPaths(array $filePaths): void return; } - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'Rector has detected a "/vendor" directory in your configured paths. If this is Composer\'s vendor directory, this is not necessary as it will be autoloaded. Scanning the Composer /vendor directory will cause Rector to run much slower and possibly with errors.%sRemove "/vendor" from Rector paths and run again.', "\n\n" )); @@ -152,7 +152,7 @@ public function reportStartWithShortOpenTag(): void $suffix = count($files) > 1 ? 's were' : ' was'; $fileList = implode("\n", $files); - $this->symfonyStyle->warning(sprintf( + $this->rectorStyle->warning(sprintf( 'The following file%s skipped as starting with short open tag. Migrate to long open PHP tag first: %s%s', $suffix, "\n\n", diff --git a/src/Util/NodePrinter.php b/src/Util/NodePrinter.php index e914692dcc4..91ca51be2e7 100644 --- a/src/Util/NodePrinter.php +++ b/src/Util/NodePrinter.php @@ -6,8 +6,8 @@ use Nette\Utils\Strings; use PhpParser\Node; +use Rector\Console\Style\RectorStyle; use Rector\CustomRules\SimpleNodeDumper; -use Symfony\Component\Console\Style\SymfonyStyle; final readonly class NodePrinter { @@ -22,7 +22,7 @@ private const string PROPERTY_KEY_REGEX = '#(?[\w\d]+)\:#'; public function __construct( - private SymfonyStyle $symfonyStyle + private RectorStyle $rectorStyle ) { } @@ -35,9 +35,9 @@ public function printNodes(Node|array $nodes): void // colorize $colorContents = $this->addConsoleColors($dumpedNodesContents); - $this->symfonyStyle->writeln($colorContents); + $this->rectorStyle->writeln($colorContents); - $this->symfonyStyle->newLine(); + $this->rectorStyle->newLine(); } private function addConsoleColors(string $contents): string diff --git a/tests/Console/Command/ComposerBasedCommandTest.php b/tests/Console/Command/ComposerBasedCommandTest.php index ec9448d7861..3ca3fb46dad 100644 --- a/tests/Console/Command/ComposerBasedCommandTest.php +++ b/tests/Console/Command/ComposerBasedCommandTest.php @@ -10,11 +10,12 @@ use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; use Rector\Console\Command\ComposerBasedCommand; +use Rector\Console\Style\RectorStyle; use Rector\Renaming\Rector\Name\RenameClassRector; use Rector\Tests\Console\Command\Source\ComposerBoundRector; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Console\Output\OutputInterface; final class ComposerBasedCommandTest extends TestCase { @@ -122,8 +123,10 @@ public function testInactiveRuleConfigurationIsReported(): void */ private function createComposerBasedCommand(array $rectors): ComposerBasedCommand { - $symfonyStyle = new SymfonyStyle(new ArrayInput([]), $this->bufferedOutput); + $rectorStyle = new RectorStyle(new ArrayInput([]), $this->bufferedOutput); + // RectorStyle is quiet under PHPUnit, output is asserted here + $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_NORMAL); - return new ComposerBasedCommand($symfonyStyle, new InstalledPackageResolver(getcwd()), $rectors); + return new ComposerBasedCommand($rectorStyle, new InstalledPackageResolver(getcwd()), $rectors); } } diff --git a/tests/Console/Command/ValidateConfigCommandTest.php b/tests/Console/Command/ValidateConfigCommandTest.php index 897c3d6ea85..f8b6f8b7929 100644 --- a/tests/Console/Command/ValidateConfigCommandTest.php +++ b/tests/Console/Command/ValidateConfigCommandTest.php @@ -10,6 +10,7 @@ use Rector\Configuration\VendorMissAnalyseGuard; use Rector\Console\Command\ValidateConfigCommand; use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyle; use Rector\Php85\Rector\FuncCall\OrdSingleByteRector; use Rector\Reporting\DeprecatedRulesReporter; use Rector\Reporting\MissConfigurationReporter; @@ -20,7 +21,7 @@ use Rector\Tests\Console\Command\Source\DeprecatedFixtureRule; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; final class ValidateConfigCommandTest extends AbstractLazyTestCase @@ -46,13 +47,15 @@ protected function setUp(): void SimpleParameterProvider::setParameter($optionName, []); } - $symfonyStyle = new SymfonyStyle(new ArrayInput([]), new BufferedOutput()); + $rectorStyle = new RectorStyle(new ArrayInput([]), new BufferedOutput()); + // RectorStyle is quiet under PHPUnit, output is asserted here + $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_NORMAL); $validateConfigCommand = new ValidateConfigCommand( - $symfonyStyle, - new DeprecatedRulesReporter($symfonyStyle), + $rectorStyle, + new DeprecatedRulesReporter($rectorStyle), new MissConfigurationReporter( - $symfonyStyle, + $rectorStyle, new VendorMissAnalyseGuard(), $this->make(UnusedSkipResolver::class), $this->make(NeededSkipVerifier::class), diff --git a/tests/Reporting/MissConfigurationReporterTest.php b/tests/Reporting/MissConfigurationReporterTest.php index a0a98664545..f4311713caa 100644 --- a/tests/Reporting/MissConfigurationReporterTest.php +++ b/tests/Reporting/MissConfigurationReporterTest.php @@ -7,6 +7,7 @@ use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; use Rector\Configuration\VendorMissAnalyseGuard; +use Rector\Console\Style\RectorStyle; use Rector\Php85\Rector\FuncCall\OrdSingleByteRector; use Rector\PostRector\Rector\NameImportingPostRector; use Rector\Reporting\MissConfigurationReporter; @@ -21,7 +22,7 @@ use Rector\ValueObject\ProcessResult; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Console\Output\OutputInterface; final class MissConfigurationReporterTest extends AbstractLazyTestCase { @@ -40,10 +41,12 @@ protected function setUp(): void parent::setUp(); $this->bufferedOutput = new BufferedOutput(); - $symfonyStyle = new SymfonyStyle(new ArrayInput([]), $this->bufferedOutput); + $rectorStyle = new RectorStyle(new ArrayInput([]), $this->bufferedOutput); + // RectorStyle is quiet under PHPUnit, output is asserted here + $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_NORMAL); $this->missConfigurationReporter = new MissConfigurationReporter( - $symfonyStyle, + $rectorStyle, new VendorMissAnalyseGuard(), $this->make(UnusedSkipResolver::class), $this->make(NeededSkipVerifier::class),