HelpCommand.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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\AbstractFixer;
  13. use PhpCsFixer\Console\Application;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\Fixer\DeprecatedFixerInterface;
  16. use PhpCsFixer\Fixer\FixerInterface;
  17. use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
  18. use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
  19. use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
  20. use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
  21. use PhpCsFixer\FixerFactory;
  22. use PhpCsFixer\Preg;
  23. use PhpCsFixer\RuleSet\RuleSet;
  24. use PhpCsFixer\RuleSet\RuleSets;
  25. use PhpCsFixer\Utils;
  26. use Symfony\Component\Console\Command\HelpCommand as BaseHelpCommand;
  27. use Symfony\Component\Console\Formatter\OutputFormatter;
  28. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  29. use Symfony\Component\Console\Input\InputInterface;
  30. use Symfony\Component\Console\Output\OutputInterface;
  31. /**
  32. * @author Fabien Potencier <fabien@symfony.com>
  33. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  34. * @author SpacePossum
  35. *
  36. * @internal
  37. */
  38. final class HelpCommand extends BaseHelpCommand
  39. {
  40. protected static $defaultName = 'help';
  41. /**
  42. * Returns help-copy suitable for console output.
  43. *
  44. * @return string
  45. */
  46. public static function getHelpCopy()
  47. {
  48. $template =
  49. <<<'EOF'
  50. The <info>%command.name%</info> command tries to fix as much coding standards
  51. problems as possible on a given file or files in a given directory and its subdirectories:
  52. <info>$ php %command.full_name% /path/to/dir</info>
  53. <info>$ php %command.full_name% /path/to/file</info>
  54. By default <comment>--path-mode</comment> is set to `override`, which means, that if you specify the path to a file or a directory via
  55. command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use <comment>--path-mode=intersection</comment>
  56. to merge paths from the config file and from the argument:
  57. <info>$ php %command.full_name% --path-mode=intersection /path/to/dir</info>
  58. The <comment>--format</comment> option for the output format. Supported formats are `txt` (default one), `json`, `xml`, `checkstyle`, `junit` and `gitlab`.
  59. NOTE: the output for the following formats are generated in accordance with XML schemas
  60. * `checkstyle` follows the common `"checkstyle" xml schema </doc/report-schema/checkstyle.xsd>`_
  61. * `junit` follows the `JUnit xml schema from Jenkins </doc/report-schema/junit-10.xsd>`_
  62. The <comment>--quiet</comment> Do not output any message.
  63. The <comment>--verbose</comment> option will show the applied rules. When using the `txt` format it will also display progress notifications.
  64. NOTE: if there is an error like "errors reported during linting after fixing", you can use this to be even more verbose for debugging purpose
  65. * `-v`: verbose
  66. * `-vv`: very verbose
  67. * `-vvv`: debug
  68. The <comment>--rules</comment> option limits the rules to apply to the
  69. project:
  70. <info>$ php %command.full_name% /path/to/project --rules=@PSR2</info>
  71. By default the PSR1 and PSR2 rules are used.
  72. The <comment>--rules</comment> option lets you choose the exact rules to
  73. apply (the rule names must be separated by a comma):
  74. <info>$ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type</info>
  75. You can also exclude the rules you don't want by placing a dash in front of the rule name, if this is more convenient,
  76. using <comment>-name_of_fixer</comment>:
  77. <info>$ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type</info>
  78. When using combinations of exact and exclude rules, applying exact rules along with above excluded results:
  79. <info>$ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison</info>
  80. Complete configuration for rules can be supplied using a `json` formatted string.
  81. <info>$ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}'</info>
  82. The <comment>--dry-run</comment> flag will run the fixer without making changes to your files.
  83. The <comment>--diff</comment> flag can be used to let the fixer output all the changes it makes.
  84. The <comment>--diff-format</comment> option allows to specify in which format the fixer should output the changes it makes:
  85. * <comment>null</comment>: no diff;
  86. * <comment>udiff</comment>: unified diff format.
  87. The <comment>--allow-risky</comment> option (pass `yes` or `no`) allows you to set whether risky rules may run. Default value is taken from config file.
  88. A rule is considered risky if it could change code behaviour. By default no risky rules are run.
  89. The <comment>--stop-on-violation</comment> flag stops the execution upon first file that needs to be fixed.
  90. The <comment>--show-progress</comment> option allows you to choose the way process progress is rendered:
  91. * <comment>none</comment>: disables progress output;
  92. * <comment>dots</comment>: multiline progress output with number of files and percentage on each line.
  93. If the option is not provided, it defaults to <comment>dots</comment> unless a config file that disables output is used, in which case it defaults to <comment>none</comment>. This option has no effect if the verbosity of the command is less than <comment>verbose</comment>.
  94. <info>$ php %command.full_name% --verbose --show-progress=dots</info>
  95. The command can also read from standard input, in which case it won't
  96. automatically fix anything:
  97. <info>$ cat foo.php | php %command.full_name% --diff -</info>
  98. Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that
  99. would be default in next MAJOR release and to forbid using deprecated configuration:
  100. <info>$ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff</info>
  101. Rules
  102. -----
  103. Use the following command to quickly understand what a rule will do to your code:
  104. <info>$ php php-cs-fixer.phar describe align_multiline_comment</info>
  105. To visualize all the rules that belong to a ruleset:
  106. <info>$ php php-cs-fixer.phar describe @PSR2</info>
  107. Choose from the list of available rules:
  108. %%%FIXERS_DETAILS%%%
  109. The <comment>--dry-run</comment> option displays the files that need to be
  110. fixed but without actually modifying them:
  111. <info>$ php %command.full_name% /path/to/code --dry-run</info>
  112. Config file
  113. -----------
  114. Instead of using command line options to customize the rule, you can save the
  115. project configuration in a <comment>.php_cs.dist</comment> file in the root directory of your project.
  116. The file must return an instance of `PhpCsFixer\ConfigInterface` (<url>%%%CONFIG_INTERFACE_URL%%%</url>)
  117. which lets you configure the rules, the files and directories that
  118. need to be analyzed. You may also create <comment>.php_cs</comment> file, which is
  119. the local configuration that will be used instead of the project configuration. It
  120. is a good practice to add that file into your <comment>.gitignore</comment> file.
  121. With the <comment>--config</comment> option you can specify the path to the
  122. <comment>.php_cs</comment> file.
  123. The example below will add two rules to the default list of PSR2 set rules:
  124. <?php
  125. $finder = PhpCsFixer\Finder::create()
  126. ->exclude('somedir')
  127. ->notPath('src/Symfony/Component/Translation/Tests/fixtures/resources.php')
  128. ->in(__DIR__)
  129. ;
  130. $config = new Config();
  131. return $config
  132. ->setRules([
  133. '@PSR2' => true,
  134. 'strict_param' => true,
  135. 'array_syntax' => ['syntax' => 'short'],
  136. ])
  137. ->setFinder($finder)
  138. ;
  139. ?>
  140. **NOTE**: `exclude` will work only for directories, so if you need to exclude file, try `notPath`.
  141. Both `exclude` and `notPath` methods accept only relative paths to the ones defined with the `in` method.
  142. See `Symfony\Finder` (<url>https://symfony.com/doc/current/components/finder.html</url>)
  143. online documentation for other `Finder` methods.
  144. You may also use an exclude list for the rules instead of the above shown include approach.
  145. The following example shows how to use all `Symfony` rules but the `full_opening_tag` rule.
  146. <?php
  147. $finder = PhpCsFixer\Finder::create()
  148. ->exclude('somedir')
  149. ->in(__DIR__)
  150. ;
  151. $config = new Config();
  152. return $config
  153. ->setRules([
  154. '@Symfony' => true,
  155. 'full_opening_tag' => false,
  156. ])
  157. ->setFinder($finder)
  158. ;
  159. ?>
  160. You may want to use non-linux whitespaces in your project. Then you need to
  161. configure them in your config file.
  162. <?php
  163. $config = new Config();
  164. return $config
  165. ->setIndent("\t")
  166. ->setLineEnding("\r\n")
  167. ;
  168. ?>
  169. By using `--using-cache` option with `yes` or `no` you can set if the caching
  170. mechanism should be used.
  171. Caching
  172. -------
  173. The caching mechanism is enabled by default. This will speed up further runs by
  174. fixing only files that were modified since the last run. The tool will fix all
  175. files if the tool version has changed or the list of rules has changed.
  176. Cache is supported only for tool downloaded as phar file or installed via
  177. composer.
  178. Cache can be disabled via `--using-cache` option or config file:
  179. <?php
  180. $config = new Config();
  181. return $config->setUsingCache(false);
  182. ?>
  183. Cache file can be specified via `--cache-file` option or config file:
  184. <?php
  185. $config = new Config();
  186. return $config->setCacheFile(__DIR__.'/.php_cs.cache');
  187. ?>
  188. Using PHP CS Fixer on CI
  189. ------------------------
  190. Require `friendsofphp/php-cs-fixer` as a `dev` dependency:
  191. $ ./composer.phar require --dev friendsofphp/php-cs-fixer
  192. Then, add the following command to your CI:
  193. %%%CI_INTEGRATION%%%
  194. Where `$COMMIT_RANGE` is your range of commits, e.g. `$TRAVIS_COMMIT_RANGE` or `HEAD~..HEAD`.
  195. Exit code
  196. ---------
  197. Exit code of the fix command is built using following bit flags:
  198. * 0 - OK.
  199. * 1 - General error (or PHP minimal requirement not matched).
  200. * 4 - Some files have invalid syntax (only in dry-run mode).
  201. * 8 - Some files need fixing (only in dry-run mode).
  202. * 16 - Configuration error of the application.
  203. * 32 - Configuration error of a Fixer.
  204. * 64 - Exception raised within the application.
  205. EOF
  206. ;
  207. return strtr($template, [
  208. '%%%CONFIG_INTERFACE_URL%%%' => sprintf(
  209. 'https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/v%s/src/ConfigInterface.php',
  210. self::getLatestReleaseVersionFromChangeLog()
  211. ),
  212. '%%%CI_INTEGRATION%%%' => implode("\n", array_map(
  213. static function ($line) { return ' $ '.$line; },
  214. \array_slice(file(__DIR__.'/../../../ci-integration.sh', FILE_IGNORE_NEW_LINES), 3)
  215. )),
  216. '%%%FIXERS_DETAILS%%%' => self::getFixersHelp(),
  217. ]);
  218. }
  219. /**
  220. * @param mixed $value
  221. *
  222. * @return string
  223. */
  224. public static function toString($value)
  225. {
  226. return \is_array($value)
  227. ? static::arrayToString($value)
  228. : static::scalarToString($value)
  229. ;
  230. }
  231. /**
  232. * Returns the allowed values of the given option that can be converted to a string.
  233. *
  234. * @return null|array
  235. */
  236. public static function getDisplayableAllowedValues(FixerOptionInterface $option)
  237. {
  238. $allowed = $option->getAllowedValues();
  239. if (null !== $allowed) {
  240. $allowed = array_filter($allowed, static function ($value) {
  241. return !($value instanceof \Closure);
  242. });
  243. usort($allowed, static function ($valueA, $valueB) {
  244. if ($valueA instanceof AllowedValueSubset) {
  245. return -1;
  246. }
  247. if ($valueB instanceof AllowedValueSubset) {
  248. return 1;
  249. }
  250. return strcasecmp(
  251. self::toString($valueA),
  252. self::toString($valueB)
  253. );
  254. });
  255. if (0 === \count($allowed)) {
  256. $allowed = null;
  257. }
  258. }
  259. return $allowed;
  260. }
  261. /**
  262. * @throws \RuntimeException when failing to parse the change log file
  263. *
  264. * @return string
  265. */
  266. public static function getLatestReleaseVersionFromChangeLog()
  267. {
  268. static $version = null;
  269. if (null !== $version) {
  270. return $version;
  271. }
  272. $changelogFile = self::getChangeLogFile();
  273. if (null === $changelogFile) {
  274. $version = Application::VERSION;
  275. return $version;
  276. }
  277. $changelog = @file_get_contents($changelogFile);
  278. if (false === $changelog) {
  279. $error = error_get_last();
  280. throw new \RuntimeException(sprintf(
  281. 'Failed to read content of the changelog file "%s".%s',
  282. $changelogFile,
  283. $error ? ' '.$error['message'] : ''
  284. ));
  285. }
  286. for ($i = Application::getMajorVersion(); $i > 0; --$i) {
  287. if (1 === Preg::match('/Changelog for v('.$i.'.\d+.\d+)/', $changelog, $matches)) {
  288. $version = $matches[1];
  289. break;
  290. }
  291. }
  292. if (null === $version) {
  293. throw new \RuntimeException(sprintf('Failed to parse changelog data of "%s".', $changelogFile));
  294. }
  295. return $version;
  296. }
  297. /**
  298. * {@inheritdoc}
  299. */
  300. protected function initialize(InputInterface $input, OutputInterface $output)
  301. {
  302. $output->getFormatter()->setStyle('url', new OutputFormatterStyle('blue'));
  303. }
  304. /**
  305. * @return null|string
  306. */
  307. private static function getChangeLogFile()
  308. {
  309. $changelogFile = __DIR__.'/../../../CHANGELOG.md';
  310. return is_file($changelogFile) ? $changelogFile : null;
  311. }
  312. /**
  313. * @return string
  314. */
  315. private static function getFixersHelp()
  316. {
  317. $help = '';
  318. $fixerFactory = new FixerFactory();
  319. /** @var AbstractFixer[] $fixers */
  320. $fixers = $fixerFactory->registerBuiltInFixers()->getFixers();
  321. // sort fixers by name
  322. usort(
  323. $fixers,
  324. static function (FixerInterface $a, FixerInterface $b) {
  325. return strcmp($a->getName(), $b->getName());
  326. }
  327. );
  328. $ruleSets = [];
  329. foreach (RuleSets::getSetDefinitionNames() as $setName) {
  330. $ruleSets[$setName] = new RuleSet([$setName => true]);
  331. }
  332. $getSetsWithRule = static function ($rule) use ($ruleSets) {
  333. $sets = [];
  334. foreach ($ruleSets as $setName => $ruleSet) {
  335. if ($ruleSet->hasRule($rule)) {
  336. $sets[] = $setName;
  337. }
  338. }
  339. return $sets;
  340. };
  341. $count = \count($fixers) - 1;
  342. foreach ($fixers as $i => $fixer) {
  343. $sets = $getSetsWithRule($fixer->getName());
  344. $description = $fixer->getDefinition()->getSummary();
  345. if ($fixer instanceof DeprecatedFixerInterface) {
  346. $successors = $fixer->getSuccessorsNames();
  347. $message = [] === $successors
  348. ? 'will be removed on next major version'
  349. : sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors));
  350. $description .= sprintf(' DEPRECATED: %s.', $message);
  351. }
  352. $description = implode("\n | ", self::wordwrap(
  353. Preg::replace('/(`.+?`)/', '<info>$1</info>', $description),
  354. 72
  355. ));
  356. if (!empty($sets)) {
  357. $help .= sprintf(" * <comment>%s</comment> [%s]\n | %s\n", $fixer->getName(), implode(', ', $sets), $description);
  358. } else {
  359. $help .= sprintf(" * <comment>%s</comment>\n | %s\n", $fixer->getName(), $description);
  360. }
  361. if ($fixer->isRisky()) {
  362. $help .= sprintf(
  363. " | *Risky rule: %s.*\n",
  364. Preg::replace(
  365. '/(`.+?`)/',
  366. '<info>$1</info>',
  367. lcfirst(Preg::replace('/\.$/', '', $fixer->getDefinition()->getRiskyDescription()))
  368. )
  369. );
  370. }
  371. if ($fixer instanceof ConfigurableFixerInterface) {
  372. $configurationDefinition = $fixer->getConfigurationDefinition();
  373. $configurationDefinitionOptions = $configurationDefinition->getOptions();
  374. if (\count($configurationDefinitionOptions)) {
  375. $help .= " |\n | Configuration options:\n";
  376. usort(
  377. $configurationDefinitionOptions,
  378. static function (FixerOptionInterface $optionA, FixerOptionInterface $optionB) {
  379. return strcmp($optionA->getName(), $optionB->getName());
  380. }
  381. );
  382. foreach ($configurationDefinitionOptions as $option) {
  383. $line = '<info>'.OutputFormatter::escape($option->getName()).'</info>';
  384. $allowed = self::getDisplayableAllowedValues($option);
  385. if (null !== $allowed) {
  386. foreach ($allowed as &$value) {
  387. if ($value instanceof AllowedValueSubset) {
  388. $value = 'a subset of <comment>'.self::toString($value->getAllowedValues()).'</comment>';
  389. } else {
  390. $value = '<comment>'.self::toString($value).'</comment>';
  391. }
  392. }
  393. } else {
  394. $allowed = array_map(
  395. static function ($type) {
  396. return '<comment>'.$type.'</comment>';
  397. },
  398. $option->getAllowedTypes()
  399. );
  400. }
  401. if (null !== $allowed) {
  402. $line .= ' ('.implode(', ', $allowed).')';
  403. }
  404. $line .= ': '.Preg::replace(
  405. '/(`.+?`)/',
  406. '<info>$1</info>',
  407. lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDescription())))
  408. ).'; ';
  409. if ($option->hasDefault()) {
  410. $line .= 'defaults to <comment>'.self::toString($option->getDefault()).'</comment>';
  411. } else {
  412. $line .= 'required';
  413. }
  414. if ($option instanceof DeprecatedFixerOption) {
  415. $line .= '. DEPRECATED: '.Preg::replace(
  416. '/(`.+?`)/',
  417. '<info>$1</info>',
  418. lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDeprecationMessage())))
  419. );
  420. }
  421. if ($option instanceof AliasedFixerOption) {
  422. $line .= '; DEPRECATED alias: <comment>'.$option->getAlias().'</comment>';
  423. }
  424. foreach (self::wordwrap($line, 72) as $index => $line) {
  425. $help .= (0 === $index ? ' | - ' : ' | ').$line."\n";
  426. }
  427. }
  428. }
  429. } elseif ($fixer instanceof ConfigurableFixerInterface) {
  430. $help .= " | *Configurable rule.*\n";
  431. }
  432. if ($count !== $i) {
  433. $help .= "\n";
  434. }
  435. }
  436. // prevent "\</foo>" from being rendered as an escaped literal style tag
  437. return Preg::replace('#\\\\(</.*?>)#', '<<$1', $help);
  438. }
  439. /**
  440. * Wraps a string to the given number of characters, ignoring style tags.
  441. *
  442. * @param string $string
  443. * @param int $width
  444. *
  445. * @return string[]
  446. */
  447. private static function wordwrap($string, $width)
  448. {
  449. $result = [];
  450. $currentLine = 0;
  451. $lineLength = 0;
  452. foreach (explode(' ', $string) as $word) {
  453. $wordLength = \strlen(Preg::replace('~</?(\w+)>~', '', $word));
  454. if (0 !== $lineLength) {
  455. ++$wordLength; // space before word
  456. }
  457. if ($lineLength + $wordLength > $width) {
  458. ++$currentLine;
  459. $lineLength = 0;
  460. }
  461. $result[$currentLine][] = $word;
  462. $lineLength += $wordLength;
  463. }
  464. return array_map(static function ($line) {
  465. return implode(' ', $line);
  466. }, $result);
  467. }
  468. /**
  469. * @param mixed $value
  470. *
  471. * @return string
  472. */
  473. private static function scalarToString($value)
  474. {
  475. $str = var_export($value, true);
  476. return Preg::replace('/\bNULL\b/', 'null', $str);
  477. }
  478. /**
  479. * @return string
  480. */
  481. private static function arrayToString(array $value)
  482. {
  483. if (0 === \count($value)) {
  484. return '[]';
  485. }
  486. $isHash = static::isHash($value);
  487. $str = '[';
  488. foreach ($value as $k => $v) {
  489. if ($isHash) {
  490. $str .= static::scalarToString($k).' => ';
  491. }
  492. $str .= \is_array($v)
  493. ? static::arrayToString($v).', '
  494. : static::scalarToString($v).', '
  495. ;
  496. }
  497. return substr($str, 0, -2).']';
  498. }
  499. /**
  500. * @return bool
  501. */
  502. private static function isHash(array $array)
  503. {
  504. $i = 0;
  505. foreach ($array as $k => $v) {
  506. if ($k !== $i) {
  507. return true;
  508. }
  509. ++$i;
  510. }
  511. return false;
  512. }
  513. }