HelpCommand.php 19 KB

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