DescribeCommand.php 14 KB

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