|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\SwissKnife\Command; |
| 6 | + |
| 7 | +use Rector\SwissKnife\Traits\TraitSpotter; |
| 8 | +use Symfony\Component\Console\Command\Command; |
| 9 | +use Symfony\Component\Console\Input\InputArgument; |
| 10 | +use Symfony\Component\Console\Input\InputInterface; |
| 11 | +use Symfony\Component\Console\Input\InputOption; |
| 12 | +use Symfony\Component\Console\Output\OutputInterface; |
| 13 | +use Symfony\Component\Console\Style\SymfonyStyle; |
| 14 | + |
| 15 | +final class TraitSpottingCommand extends Command |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + private readonly SymfonyStyle $symfonyStyle, |
| 19 | + private readonly TraitSpotter $traitSpotter, |
| 20 | + ) { |
| 21 | + parent::__construct(); |
| 22 | + } |
| 23 | + |
| 24 | + protected function configure(): void |
| 25 | + { |
| 26 | + $this->setName('trait-spotting'); |
| 27 | + |
| 28 | + $this->addArgument( |
| 29 | + 'sources', |
| 30 | + InputArgument::REQUIRED | InputArgument::IS_ARRAY, |
| 31 | + 'One or more paths to check' |
| 32 | + ); |
| 33 | + |
| 34 | + $this->addOption('max-used', null, InputOption::VALUE_REQUIRED, 'Maximum count the trait is used', 2); |
| 35 | + |
| 36 | + $this->setDescription( |
| 37 | + 'Spot traits that are use only once, to potentially inline them and make code more robust and readable' |
| 38 | + ); |
| 39 | + } |
| 40 | + |
| 41 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 42 | + { |
| 43 | + $sources = (array) $input->getArgument('sources'); |
| 44 | + $maxUsedCount = (int) $input->getArgument('max-used'); |
| 45 | + |
| 46 | + $this->symfonyStyle->title('Analysing single-used traits, shorter first'); |
| 47 | + $traitSpottingResult = $this->traitSpotter->analyse($sources); |
| 48 | + |
| 49 | + $this->symfonyStyle->note(sprintf('Found %d traits', $traitSpottingResult->getTraitCount())); |
| 50 | + |
| 51 | + $maxTimesUsedTraits = $traitSpottingResult->getTraitMaximumUsedTimes($maxUsedCount); |
| 52 | + |
| 53 | + foreach ($maxTimesUsedTraits as $traitUsage) { |
| 54 | + $this->symfonyStyle->writeln(sprintf( |
| 55 | + 'Trait "%s" (%d lines) is used only in %d files', |
| 56 | + $traitUsage->shortTraitName, |
| 57 | + $traitUsage->lineCount, |
| 58 | + count($traitUsage->usingFiles) |
| 59 | + )); |
| 60 | + $this->symfonyStyle->newLine(); |
| 61 | + |
| 62 | + $this->symfonyStyle->listing($traitUsage->usingFiles); |
| 63 | + $this->symfonyStyle->newLine(); |
| 64 | + } |
| 65 | + |
| 66 | + $this->symfonyStyle->newLine(); |
| 67 | + |
| 68 | + $this->symfonyStyle->warning(sprintf( |
| 69 | + 'Found %d traits, the less the better to make dependencies explicit', |
| 70 | + count($maxTimesUsedTraits) |
| 71 | + )); |
| 72 | + |
| 73 | + return self::SUCCESS; |
| 74 | + } |
| 75 | +} |
0 commit comments