DescribeCommand.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Console\Command;
  13. use PhpCsFixer\Config;
  14. use PhpCsFixer\Console\Application;
  15. use PhpCsFixer\Console\ConfigurationResolver;
  16. use PhpCsFixer\Differ\DiffConsoleFormatter;
  17. use PhpCsFixer\Differ\FullDiffer;
  18. use PhpCsFixer\Documentation\FixerDocumentGenerator;
  19. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  20. use PhpCsFixer\Fixer\DeprecatedFixerInterface;
  21. use PhpCsFixer\Fixer\ExperimentalFixerInterface;
  22. use PhpCsFixer\Fixer\FixerInterface;
  23. use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
  24. use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
  25. use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
  26. use PhpCsFixer\FixerDefinition\CodeSampleInterface;
  27. use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
  28. use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
  29. use PhpCsFixer\FixerFactory;
  30. use PhpCsFixer\Preg;
  31. use PhpCsFixer\RuleSet\RuleSets;
  32. use PhpCsFixer\StdinFileInfo;
  33. use PhpCsFixer\Tokenizer\Tokens;
  34. use PhpCsFixer\ToolInfo;
  35. use PhpCsFixer\Utils;
  36. use PhpCsFixer\WordMatcher;
  37. use Symfony\Component\Console\Attribute\AsCommand;
  38. use Symfony\Component\Console\Command\Command;
  39. use Symfony\Component\Console\Formatter\OutputFormatter;
  40. use Symfony\Component\Console\Input\InputArgument;
  41. use Symfony\Component\Console\Input\InputInterface;
  42. use Symfony\Component\Console\Input\InputOption;
  43. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  44. use Symfony\Component\Console\Output\OutputInterface;
  45. /**
  46. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  47. *
  48. * @internal
  49. */
  50. #[AsCommand(name: 'describe')]
  51. final class DescribeCommand extends Command
  52. {
  53. /** @var string */
  54. protected static $defaultName = 'describe';
  55. /**
  56. * @var ?list<string>
  57. */
  58. private $setNames;
  59. private FixerFactory $fixerFactory;
  60. /**
  61. * @var array<string, FixerInterface>
  62. */
  63. private $fixers;
  64. public function __construct(?FixerFactory $fixerFactory = null)
  65. {
  66. parent::__construct();
  67. if (null === $fixerFactory) {
  68. $fixerFactory = new FixerFactory();
  69. $fixerFactory->registerBuiltInFixers();
  70. }
  71. $this->fixerFactory = $fixerFactory;
  72. }
  73. protected function configure(): void
  74. {
  75. $this
  76. ->setDefinition(
  77. [
  78. new InputArgument('name', InputArgument::REQUIRED, 'Name of rule / set.'),
  79. new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'),
  80. ]
  81. )
  82. ->setDescription('Describe rule / ruleset.')
  83. ;
  84. }
  85. protected function execute(InputInterface $input, OutputInterface $output): int
  86. {
  87. if ($output instanceof ConsoleOutputInterface) {
  88. $stdErr = $output->getErrorOutput();
  89. $stdErr->writeln(Application::getAboutWithRuntime(true));
  90. }
  91. $resolver = new ConfigurationResolver(
  92. new Config(),
  93. ['config' => $input->getOption('config')],
  94. getcwd(),
  95. new ToolInfo()
  96. );
  97. $this->fixerFactory->registerCustomFixers($resolver->getConfig()->getCustomFixers());
  98. $name = $input->getArgument('name');
  99. try {
  100. if (str_starts_with($name, '@')) {
  101. $this->describeSet($output, $name);
  102. return 0;
  103. }
  104. $this->describeRule($output, $name);
  105. } catch (DescribeNameNotFoundException $e) {
  106. $matcher = new WordMatcher(
  107. 'set' === $e->getType() ? $this->getSetNames() : array_keys($this->getFixers())
  108. );
  109. $alternative = $matcher->match($name);
  110. $this->describeList($output, $e->getType());
  111. throw new \InvalidArgumentException(sprintf(
  112. '%s "%s" not found.%s',
  113. ucfirst($e->getType()),
  114. $name,
  115. null === $alternative ? '' : ' Did you mean "'.$alternative.'"?'
  116. ));
  117. }
  118. return 0;
  119. }
  120. private function describeRule(OutputInterface $output, string $name): void
  121. {
  122. $fixers = $this->getFixers();
  123. if (!isset($fixers[$name])) {
  124. throw new DescribeNameNotFoundException($name, 'rule');
  125. }
  126. /** @var FixerInterface $fixer */
  127. $fixer = $fixers[$name];
  128. $definition = $fixer->getDefinition();
  129. $output->writeln(sprintf('<fg=blue>Description of the <info>`%s`</info> rule.</>', $name));
  130. $output->writeln('');
  131. if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
  132. $output->writeln(sprintf('Fixer class: <comment>%s</comment>.', \get_class($fixer)));
  133. $output->writeln('');
  134. }
  135. if ($fixer instanceof DeprecatedFixerInterface) {
  136. $successors = $fixer->getSuccessorsNames();
  137. $message = [] === $successors
  138. ? sprintf('it will be removed in version %d.0', Application::getMajorVersion() + 1)
  139. : sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors));
  140. $endMessage = '. '.ucfirst($message);
  141. Utils::triggerDeprecation(new \RuntimeException(str_replace('`', '"', "Rule \"{$name}\" is deprecated{$endMessage}.")));
  142. $message = Preg::replace('/(`[^`]+`)/', '<info>$1</info>', $message);
  143. $output->writeln(sprintf('<error>DEPRECATED</error>: %s.', $message));
  144. $output->writeln('');
  145. }
  146. $output->writeln($definition->getSummary());
  147. $description = $definition->getDescription();
  148. if (null !== $description) {
  149. $output->writeln($description);
  150. }
  151. $output->writeln('');
  152. if ($fixer instanceof ExperimentalFixerInterface) {
  153. $output->writeln('<error>Fixer applying this rule is EXPERIMENTAL.</error>.');
  154. $output->writeln('It is not covered with backward compatibility promise and may produce unstable or unexpected results.');
  155. $output->writeln('');
  156. }
  157. if ($fixer->isRisky()) {
  158. $output->writeln('<error>Fixer applying this rule is RISKY.</error>');
  159. $riskyDescription = $definition->getRiskyDescription();
  160. if (null !== $riskyDescription) {
  161. $output->writeln($riskyDescription);
  162. }
  163. $output->writeln('');
  164. }
  165. if ($fixer instanceof ConfigurableFixerInterface) {
  166. $configurationDefinition = $fixer->getConfigurationDefinition();
  167. $options = $configurationDefinition->getOptions();
  168. $output->writeln(sprintf('Fixer is configurable using following option%s:', 1 === \count($options) ? '' : 's'));
  169. foreach ($options as $option) {
  170. $line = '* <info>'.OutputFormatter::escape($option->getName()).'</info>';
  171. $allowed = HelpCommand::getDisplayableAllowedValues($option);
  172. if (null === $allowed) {
  173. $allowed = array_map(
  174. static fn (string $type): string => '<comment>'.$type.'</comment>',
  175. $option->getAllowedTypes(),
  176. );
  177. } else {
  178. $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset
  179. ? 'a subset of <comment>'.Utils::toString($value->getAllowedValues()).'</comment>'
  180. : '<comment>'.Utils::toString($value).'</comment>', $allowed);
  181. }
  182. $line .= ' ('.Utils::naturalLanguageJoin($allowed, '').')';
  183. $description = Preg::replace('/(`.+?`)/', '<info>$1</info>', OutputFormatter::escape($option->getDescription()));
  184. $line .= ': '.lcfirst(Preg::replace('/\.$/', '', $description)).'; ';
  185. if ($option->hasDefault()) {
  186. $line .= sprintf(
  187. 'defaults to <comment>%s</comment>',
  188. Utils::toString($option->getDefault())
  189. );
  190. } else {
  191. $line .= '<comment>required</comment>';
  192. }
  193. if ($option instanceof DeprecatedFixerOption) {
  194. $line .= '. <error>DEPRECATED</error>: '.Preg::replace(
  195. '/(`.+?`)/',
  196. '<info>$1</info>',
  197. OutputFormatter::escape(lcfirst($option->getDeprecationMessage()))
  198. );
  199. }
  200. if ($option instanceof AliasedFixerOption) {
  201. $line .= '; <error>DEPRECATED</error> alias: <comment>'.$option->getAlias().'</comment>';
  202. }
  203. $output->writeln($line);
  204. }
  205. $output->writeln('');
  206. }
  207. /** @var list<CodeSampleInterface> $codeSamples */
  208. $codeSamples = array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample): bool {
  209. if ($codeSample instanceof VersionSpecificCodeSampleInterface) {
  210. return $codeSample->isSuitableFor(\PHP_VERSION_ID);
  211. }
  212. return true;
  213. });
  214. if (0 === \count($definition->getCodeSamples())) {
  215. $output->writeln([
  216. 'Fixing examples are not available for this rule.',
  217. '',
  218. ]);
  219. } elseif (0 === \count($codeSamples)) {
  220. $output->writeln([
  221. 'Fixing examples <error>cannot be</error> demonstrated on the current PHP version.',
  222. '',
  223. ]);
  224. } else {
  225. $output->writeln('Fixing examples:');
  226. $differ = new FullDiffer();
  227. $diffFormatter = new DiffConsoleFormatter(
  228. $output->isDecorated(),
  229. sprintf(
  230. '<comment> ---------- begin diff ----------</comment>%s%%s%s<comment> ----------- end diff -----------</comment>',
  231. PHP_EOL,
  232. PHP_EOL
  233. )
  234. );
  235. foreach ($codeSamples as $index => $codeSample) {
  236. $old = $codeSample->getCode();
  237. $tokens = Tokens::fromCode($old);
  238. $configuration = $codeSample->getConfiguration();
  239. if ($fixer instanceof ConfigurableFixerInterface) {
  240. $fixer->configure($configuration ?? []);
  241. }
  242. $file = $codeSample instanceof FileSpecificCodeSampleInterface
  243. ? $codeSample->getSplFileInfo()
  244. : new StdinFileInfo();
  245. $fixer->fix($file, $tokens);
  246. $diff = $differ->diff($old, $tokens->generateCode());
  247. if ($fixer instanceof ConfigurableFixerInterface) {
  248. if (null === $configuration) {
  249. $output->writeln(sprintf(' * Example #%d. Fixing with the <comment>default</comment> configuration.', $index + 1));
  250. } else {
  251. $output->writeln(sprintf(' * Example #%d. Fixing with configuration: <comment>%s</comment>.', $index + 1, Utils::toString($codeSample->getConfiguration())));
  252. }
  253. } else {
  254. $output->writeln(sprintf(' * Example #%d.', $index + 1));
  255. }
  256. $output->writeln([$diffFormatter->format($diff, ' %s'), '']);
  257. }
  258. }
  259. $ruleSetConfigs = FixerDocumentGenerator::getSetsOfRule($name);
  260. if ([] !== $ruleSetConfigs) {
  261. ksort($ruleSetConfigs);
  262. $plural = 1 !== \count($ruleSetConfigs) ? 's' : '';
  263. $output->writeln("Fixer is part of the following rule set{$plural}:");
  264. foreach ($ruleSetConfigs as $set => $config) {
  265. if (null !== $config) {
  266. $output->writeln(sprintf('* <info>%s</info> with config: <comment>%s</comment>', $set, Utils::toString($config)));
  267. } else {
  268. $output->writeln(sprintf('* <info>%s</info> with <comment>default</comment> config', $set));
  269. }
  270. }
  271. $output->writeln('');
  272. }
  273. }
  274. private function describeSet(OutputInterface $output, string $name): void
  275. {
  276. if (!\in_array($name, $this->getSetNames(), true)) {
  277. throw new DescribeNameNotFoundException($name, 'set');
  278. }
  279. $ruleSetDefinitions = RuleSets::getSetDefinitions();
  280. $fixers = $this->getFixers();
  281. $output->writeln(sprintf('<fg=blue>Description of the <info>`%s`</info> set.</>', $ruleSetDefinitions[$name]->getName()));
  282. $output->writeln('');
  283. $output->writeln($this->replaceRstLinks($ruleSetDefinitions[$name]->getDescription()));
  284. $output->writeln('');
  285. if ($ruleSetDefinitions[$name]->isRisky()) {
  286. $output->writeln('<error>This set contains risky rules.</error>');
  287. $output->writeln('');
  288. }
  289. $help = '';
  290. foreach ($ruleSetDefinitions[$name]->getRules() as $rule => $config) {
  291. if (str_starts_with($rule, '@')) {
  292. $set = $ruleSetDefinitions[$rule];
  293. $help .= sprintf(
  294. " * <info>%s</info>%s\n | %s\n\n",
  295. $rule,
  296. $set->isRisky() ? ' <error>risky</error>' : '',
  297. $this->replaceRstLinks($set->getDescription())
  298. );
  299. continue;
  300. }
  301. /** @var FixerInterface $fixer */
  302. $fixer = $fixers[$rule];
  303. $definition = $fixer->getDefinition();
  304. $help .= sprintf(
  305. " * <info>%s</info>%s\n | %s\n%s\n",
  306. $rule,
  307. $fixer->isRisky() ? ' <error>risky</error>' : '',
  308. $definition->getSummary(),
  309. true !== $config ? sprintf(" <comment>| Configuration: %s</comment>\n", Utils::toString($config)) : ''
  310. );
  311. }
  312. $output->write($help);
  313. }
  314. /**
  315. * @return array<string, FixerInterface>
  316. */
  317. private function getFixers(): array
  318. {
  319. if (null !== $this->fixers) {
  320. return $this->fixers;
  321. }
  322. $fixers = [];
  323. foreach ($this->fixerFactory->getFixers() as $fixer) {
  324. $fixers[$fixer->getName()] = $fixer;
  325. }
  326. $this->fixers = $fixers;
  327. ksort($this->fixers);
  328. return $this->fixers;
  329. }
  330. /**
  331. * @return list<string>
  332. */
  333. private function getSetNames(): array
  334. {
  335. if (null !== $this->setNames) {
  336. return $this->setNames;
  337. }
  338. $this->setNames = RuleSets::getSetDefinitionNames();
  339. return $this->setNames;
  340. }
  341. /**
  342. * @param string $type 'rule'|'set'
  343. */
  344. private function describeList(OutputInterface $output, string $type): void
  345. {
  346. if ($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
  347. return;
  348. }
  349. if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'set' === $type) {
  350. $output->writeln('<comment>Defined sets:</comment>');
  351. $items = $this->getSetNames();
  352. foreach ($items as $item) {
  353. $output->writeln(sprintf('* <info>%s</info>', $item));
  354. }
  355. }
  356. if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'rule' === $type) {
  357. $output->writeln('<comment>Defined rules:</comment>');
  358. $items = array_keys($this->getFixers());
  359. foreach ($items as $item) {
  360. $output->writeln(sprintf('* <info>%s</info>', $item));
  361. }
  362. }
  363. }
  364. private function replaceRstLinks(string $content): string
  365. {
  366. return Preg::replaceCallback(
  367. '/(`[^<]+<[^>]+>`_)/',
  368. static fn (array $matches) => Preg::replaceCallback(
  369. '/`(.*)<(.*)>`_/',
  370. static fn (array $matches): string => $matches[1].'('.$matches[2].')',
  371. $matches[1]
  372. ),
  373. $content
  374. );
  375. }
  376. }