Просмотр исходного кода

FixCommand - Support rules with params

Phan Thanh Cong 8 лет назад
Родитель
Сommit
dc7eda6996

+ 19 - 9
README.rst

@@ -124,6 +124,14 @@ problems as possible on a given file or files in a given directory and its subdi
     $ php php-cs-fixer.phar fix /path/to/dir
     $ php php-cs-fixer.phar fix /path/to/dir
     $ php php-cs-fixer.phar fix /path/to/file
     $ php php-cs-fixer.phar fix /path/to/file
 
 
+By default ``--path-mode`` is set to ``override``, which means, that if you specify the path to a file or a directory via 
+command arguments, then the paths provided to a ``Finder`` in config file will be ignored. You can use ``--path-mode=intersection`` 
+to merge paths from the config file and from the argument:
+
+.. code-block:: bash
+
+    $ php php-cs-fixer.phar fix --path-mode=intersection /path/to/dir
+
 The ``--format`` option for the output format. Supported formats are ``txt`` (default one), ``json``, ``xml`` and ``junit``.
 The ``--format`` option for the output format. Supported formats are ``txt`` (default one), ``json``, ``xml`` and ``junit``.
 
 
 NOTE: When using ``junit`` format report generates in accordance with JUnit xml schema from Jenkins (see docs/junit-10.xsd).
 NOTE: When using ``junit`` format report generates in accordance with JUnit xml schema from Jenkins (see docs/junit-10.xsd).
@@ -207,7 +215,7 @@ Choose from the list of available rules:
    | *Rule is: configurable.*
    | *Rule is: configurable.*
 
 
 * **class_keyword_remove**
 * **class_keyword_remove**
-   | Converts ::class keywords to FQCN strings. Requires PHP >= 5.5.
+   | Converts ``::class`` keywords to FQCN strings. Requires PHP >= 5.5.
 
 
 * **combine_consecutive_unsets**
 * **combine_consecutive_unsets**
    | Calling ``unset`` on multiple items should be done in one call.
    | Calling ``unset`` on multiple items should be done in one call.
@@ -240,8 +248,8 @@ Choose from the list of available rules:
    | *Rule is: risky.*
    | *Rule is: risky.*
 
 
 * **full_opening_tag** [@PSR1, @PSR2, @Symfony]
 * **full_opening_tag** [@PSR1, @PSR2, @Symfony]
-   | PHP code must use the long <?php ?> tags or the short-echo <?= ?> tags;
-   | it must not use the other tag variations.
+   | PHP code must use the long ``<?php`` tags or short-echo ``<?=`` tags and not
+   | other tag variations.
 
 
 * **function_declaration** [@PSR2, @Symfony]
 * **function_declaration** [@PSR2, @Symfony]
    | Spaces should be properly placed in a function declaration.
    | Spaces should be properly placed in a function declaration.
@@ -357,20 +365,20 @@ Choose from the list of available rules:
    | *Rule is: configurable.*
    | *Rule is: configurable.*
 
 
 * **no_multiline_whitespace_around_double_arrow** [@Symfony]
 * **no_multiline_whitespace_around_double_arrow** [@Symfony]
-   | Operator => should not be surrounded by multi-line whitespaces.
+   | Operator ``=>`` should not be surrounded by multi-line whitespaces.
 
 
 * **no_multiline_whitespace_before_semicolons**
 * **no_multiline_whitespace_before_semicolons**
    | Multi-line whitespace before closing semicolon are prohibited.
    | Multi-line whitespace before closing semicolon are prohibited.
 
 
 * **no_php4_constructor**
 * **no_php4_constructor**
-   | Convert PHP4-style constructors to __construct.
+   | Convert PHP4-style constructors to ``__construct``.
    | *Rule is: risky.*
    | *Rule is: risky.*
 
 
 * **no_short_bool_cast** [@Symfony]
 * **no_short_bool_cast** [@Symfony]
    | Short cast ``bool`` using double exclamation mark should not be used.
    | Short cast ``bool`` using double exclamation mark should not be used.
 
 
 * **no_short_echo_tag**
 * **no_short_echo_tag**
-   | Replace short-echo <?= with long format <?php echo syntax.
+   | Replace short-echo ``<?=`` with long format ``<?php echo`` syntax.
 
 
 * **no_singleline_whitespace_before_semicolons** [@Symfony]
 * **no_singleline_whitespace_before_semicolons** [@Symfony]
    | Single-line whitespace before closing semicolon are prohibited.
    | Single-line whitespace before closing semicolon are prohibited.
@@ -426,13 +434,15 @@ Choose from the list of available rules:
    | Array index should always be written by using square braces.
    | Array index should always be written by using square braces.
 
 
 * **not_operator_with_space**
 * **not_operator_with_space**
-   | Logical NOT operators (!) should have leading and trailing whitespaces.
+   | Logical NOT operators (``!``) should have leading and trailing
+   | whitespaces.
 
 
 * **not_operator_with_successor_space**
 * **not_operator_with_successor_space**
-   | Logical NOT operators (!) should have one trailing whitespace.
+   | Logical NOT operators (``!``) should have one trailing whitespace.
 
 
 * **object_operator_without_whitespace** [@Symfony]
 * **object_operator_without_whitespace** [@Symfony]
-   | There should not be space before or after object T_OBJECT_OPERATOR.
+   | There should not be space before or after object ``T_OBJECT_OPERATOR``
+   | ``->``.
 
 
 * **ordered_class_elements**
 * **ordered_class_elements**
    | Orders the elements of classes/interfaces/traits.
    | Orders the elements of classes/interfaces/traits.

+ 1 - 1
UPGRADE.md

@@ -31,7 +31,7 @@ CLI options
 --fixers        |                 | Coding standard fixers                                                    | option was removed, see --rules
 --fixers        |                 | Coding standard fixers                                                    | option was removed, see --rules
 --format        | --format        | Choose format                                                             |
 --format        | --format        | Choose format                                                             |
 --level         |                 | Coding standard level                                                     | option was removed, see --rules
 --level         |                 | Coding standard level                                                     | option was removed, see --rules
-                | --path-mode     | Should the finder from config be<br/>overriden or intersected with `path` arg | option was added
+                | --path-mode     | Should the finder from config be<br/>overridden or intersected with `path` arg | option was added
                 | --rules         | Rules to be used                                                          | option was added
                 | --rules         | Rules to be used                                                          | option was added
                 | --using-cache   | Does cache should be used                                                 | option was added
                 | --using-cache   | Does cache should be used                                                 | option was added
 
 

+ 1 - 0
composer.json

@@ -22,6 +22,7 @@
         "symfony/filesystem": "^2.4 || ^3.0",
         "symfony/filesystem": "^2.4 || ^3.0",
         "symfony/finder": "^2.2 || ^3.0",
         "symfony/finder": "^2.2 || ^3.0",
         "symfony/polyfill-php54": "^1.0",
         "symfony/polyfill-php54": "^1.0",
+        "symfony/polyfill-php55": "^1.3",
         "symfony/process": "^2.3 || ^3.0",
         "symfony/process": "^2.3 || ^3.0",
         "symfony/stopwatch": "^2.5 || ^3.0"
         "symfony/stopwatch": "^2.5 || ^3.0"
     },
     },

+ 0 - 8
src/AbstractFixer.php

@@ -17,7 +17,6 @@ use PhpCsFixer\Fixer\ConfigurableFixerInterface;
 use PhpCsFixer\Fixer\DefinedFixerInterface;
 use PhpCsFixer\Fixer\DefinedFixerInterface;
 use PhpCsFixer\Fixer\FixerInterface;
 use PhpCsFixer\Fixer\FixerInterface;
 use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
 use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
-use PhpCsFixer\FixerDefinition\ShortFixerDefinition;
 
 
 /**
 /**
  * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
@@ -90,13 +89,6 @@ abstract class AbstractFixer implements FixerInterface, DefinedFixerInterface
         $this->whitespacesConfig = $config;
         $this->whitespacesConfig = $config;
     }
     }
 
 
-    public function getDefinition()
-    {
-        return new ShortFixerDefinition(
-            $this->getDescription()
-        );
-    }
-
     private function getDefaultWhitespacesFixerConfig()
     private function getDefaultWhitespacesFixerConfig()
     {
     {
         static $defaultWhitespacesFixerConfig = null;
         static $defaultWhitespacesFixerConfig = null;

+ 8 - 4
src/Console/Command/DescribeCommand.php

@@ -18,8 +18,9 @@ use PhpCsFixer\Fixer\ConfigurableFixerInterface;
 use PhpCsFixer\Fixer\DefinedFixerInterface;
 use PhpCsFixer\Fixer\DefinedFixerInterface;
 use PhpCsFixer\Fixer\FixerInterface;
 use PhpCsFixer\Fixer\FixerInterface;
 use PhpCsFixer\FixerDefinition\CodeSampleInterface;
 use PhpCsFixer\FixerDefinition\CodeSampleInterface;
+use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
+use PhpCsFixer\FixerDefinition\FixerDefinition;
 use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
 use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
-use PhpCsFixer\FixerDefinition\ShortFixerDefinition;
 use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
 use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
 use PhpCsFixer\FixerFactory;
 use PhpCsFixer\FixerFactory;
 use PhpCsFixer\RuleSet;
 use PhpCsFixer\RuleSet;
@@ -106,7 +107,7 @@ final class DescribeCommand extends Command
         if ($fixer instanceof DefinedFixerInterface) {
         if ($fixer instanceof DefinedFixerInterface) {
             $definition = $fixer->getDefinition();
             $definition = $fixer->getDefinition();
         } else {
         } else {
-            $definition = new ShortFixerDefinition('Description is not available.');
+            $definition = new FixerDefinition('Description is not available.', array());
         }
         }
 
 
         $output->writeln(sprintf('<info>Description of</info> %s <info>rule</info>.', $name));
         $output->writeln(sprintf('<info>Description of</info> %s <info>rule</info>.', $name));
@@ -170,7 +171,10 @@ final class DescribeCommand extends Command
                     $fixer->configure($codeSample->getConfiguration());
                     $fixer->configure($codeSample->getConfiguration());
                 }
                 }
 
 
-                $fixer->fix(new StdinFileInfo(), $tokens);
+                $file = $codeSample instanceof FileSpecificCodeSampleInterface
+                    ? $codeSample->getSplFileInfo()
+                    : new StdinFileInfo();
+                $fixer->fix($file, $tokens);
                 $new = $tokens->generateCode();
                 $new = $tokens->generateCode();
                 $diff = $differ->diff($old, $new);
                 $diff = $differ->diff($old, $new);
 
 
@@ -184,7 +188,7 @@ final class DescribeCommand extends Command
             }
             }
         }
         }
 
 
-        if ($definition instanceof ShortFixerDefinition) {
+        if (!($fixer instanceof DefinedFixerInterface)) {
             $output->writeln(sprintf('<question>This rule is not yet described, do you want to help us and describe it?</question>'));
             $output->writeln(sprintf('<question>This rule is not yet described, do you want to help us and describe it?</question>'));
             $output->writeln('Contribute at <comment>https://github.com/FriendsOfPHP/PHP-CS-Fixer</comment> !');
             $output->writeln('Contribute at <comment>https://github.com/FriendsOfPHP/PHP-CS-Fixer</comment> !');
             $output->writeln('');
             $output->writeln('');

+ 6 - 0
src/Console/Command/FixCommandHelp.php

@@ -40,6 +40,12 @@ problems as possible on a given file or files in a given directory and its subdi
     <info>$ php %command.full_name% /path/to/dir</info>
     <info>$ php %command.full_name% /path/to/dir</info>
     <info>$ php %command.full_name% /path/to/file</info>
     <info>$ php %command.full_name% /path/to/file</info>
 
 
+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 
+command arguments, then the paths provided to a ``Finder`` in config file will be ignored. You can use <comment>--path-mode=intersection</comment> 
+to merge paths from the config file and from the argument:
+
+    <info>$ php %command.full_name% --path-mode=intersection /path/to/dir</info>
+
 The <comment>--format</comment> option for the output format. Supported formats are ``txt`` (default one), ``json``, ``xml`` and ``junit``.
 The <comment>--format</comment> option for the output format. Supported formats are ``txt`` (default one), ``json``, ``xml`` and ``junit``.
 
 
 NOTE: When using ``junit`` format report generates in accordance with JUnit xml schema from Jenkins (see docs/junit-10.xsd).
 NOTE: When using ``junit`` format report generates in accordance with JUnit xml schema from Jenkins (see docs/junit-10.xsd).

+ 11 - 0
src/Console/ConfigurationResolver.php

@@ -588,6 +588,17 @@ final class ConfigurationResolver
             return $this->getConfig()->getRules();
             return $this->getConfig()->getRules();
         }
         }
 
 
+        $rules = trim($this->options['rules']);
+
+        if ($rules[0] === '{') {
+            $rules = json_decode($rules, true);
+            if (JSON_ERROR_NONE !== json_last_error()) {
+                throw new InvalidConfigurationException(sprintf('Invalid JSON rules input: %s.', json_last_error_msg()));
+            }
+
+            return $rules;
+        }
+
         $rules = array();
         $rules = array();
 
 
         foreach (array_map('trim', explode(',', $this->options['rules'])) as $rule) {
         foreach (array_map('trim', explode(',', $this->options['rules'])) as $rule) {

+ 3 - 3
src/Fixer/ArrayNotation/ArraySyntaxFixer.php

@@ -38,14 +38,14 @@ final class ArraySyntaxFixer extends AbstractFixer implements ConfigurableFixerI
         'syntax' => 'long',
         'syntax' => 'long',
     );
     );
 
 
-    private $config = array();
+    private $config;
     private $candidateTokenKind;
     private $candidateTokenKind;
     private $fixCallback;
     private $fixCallback;
 
 
     /**
     /**
      * Use 'syntax' => 'long'|'short'.
      * Use 'syntax' => 'long'|'short'.
      *
      *
-     * @param array|null $configuration
+     * @param array<string, string>|null $configuration
      *
      *
      * @throws InvalidFixerConfigurationException
      * @throws InvalidFixerConfigurationException
      */
      */
@@ -107,7 +107,7 @@ final class ArraySyntaxFixer extends AbstractFixer implements ConfigurableFixerI
                 ),
                 ),
             ),
             ),
             null,
             null,
-            'The following can be configured: `only_untyped => "long"|"short"`',
+            'The following can be configured: `syntax => "long"|"short"`',
             self::$defaultConfiguration
             self::$defaultConfiguration
         );
         );
     }
     }

+ 15 - 10
src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php

@@ -13,6 +13,8 @@
 namespace PhpCsFixer\Fixer\ArrayNotation;
 namespace PhpCsFixer\Fixer\ArrayNotation;
 
 
 use PhpCsFixer\AbstractFixer;
 use PhpCsFixer\AbstractFixer;
+use PhpCsFixer\FixerDefinition\CodeSample;
+use PhpCsFixer\FixerDefinition\FixerDefinition;
 use PhpCsFixer\Tokenizer\Token;
 use PhpCsFixer\Tokenizer\Token;
 use PhpCsFixer\Tokenizer\Tokens;
 use PhpCsFixer\Tokenizer\Tokens;
 
 
@@ -23,14 +25,6 @@ use PhpCsFixer\Tokenizer\Tokens;
  */
  */
 final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer
 final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer
 {
 {
-    /**
-     * {@inheritdoc}
-     */
-    public function isCandidate(Tokens $tokens)
-    {
-        return $tokens->isTokenKindFound(T_DOUBLE_ARROW);
-    }
-
     /**
     /**
      * {@inheritdoc}
      * {@inheritdoc}
      */
      */
@@ -49,6 +43,17 @@ final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer
         }
         }
     }
     }
 
 
+    /**
+     * {@inheritdoc}
+     */
+    public function getDefinition()
+    {
+        return new FixerDefinition(
+            'Operator `=>` should not be surrounded by multi-line whitespaces.',
+            array(new CodeSample("<?php\n\$a = array(1\n\n=> 2);"))
+        );
+    }
+
     /**
     /**
      * {@inheritdoc}
      * {@inheritdoc}
      */
      */
@@ -61,9 +66,9 @@ final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer
     /**
     /**
      * {@inheritdoc}
      * {@inheritdoc}
      */
      */
-    protected function getDescription()
+    public function isCandidate(Tokens $tokens)
     {
     {
-        return 'Operator => should not be surrounded by multi-line whitespaces.';
+        return $tokens->isTokenKindFound(T_DOUBLE_ARROW);
     }
     }
 
 
     private function fixWhitespace(Token $token)
     private function fixWhitespace(Token $token)

+ 27 - 2
src/Fixer/Basic/Psr0Fixer.php

@@ -14,6 +14,8 @@ namespace PhpCsFixer\Fixer\Basic;
 
 
 use PhpCsFixer\AbstractPsrAutoloadingFixer;
 use PhpCsFixer\AbstractPsrAutoloadingFixer;
 use PhpCsFixer\Fixer\ConfigurableFixerInterface;
 use PhpCsFixer\Fixer\ConfigurableFixerInterface;
+use PhpCsFixer\FixerDefinition\FileSpecificCodeSample;
+use PhpCsFixer\FixerDefinition\FixerDefinition;
 use PhpCsFixer\Tokenizer\Tokens;
 use PhpCsFixer\Tokenizer\Tokens;
 
 
 /**
 /**
@@ -143,8 +145,31 @@ final class Psr0Fixer extends AbstractPsrAutoloadingFixer implements Configurabl
     /**
     /**
      * {@inheritdoc}
      * {@inheritdoc}
      */
      */
-    protected function getDescription()
+    public function getDefinition()
     {
     {
-        return 'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.';
+        return new FixerDefinition(
+            'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.',
+            array(
+                new FileSpecificCodeSample(
+                    '<?php
+namespace PhpCsFixer\FIXER\Basic;
+class InvalidName {}
+',
+                    new \SplFileInfo(__FILE__)
+                ),
+                new FileSpecificCodeSample(
+                    '<?php
+namespace PhpCsFixer\FIXER\Basic;
+class InvalidName {}
+',
+                    new \SplFileInfo(__FILE__),
+                    array('dir' => realpath(__DIR__.'/../..'))
+                ),
+            ),
+            null,
+            'One could set up `dir` where the code is placed under project location.',
+            self::$defaultConfiguration,
+            'This fixer may change you class name, which will break the code that is depended on old name.'
+        );
     }
     }
 }
 }

Некоторые файлы не были показаны из-за большого количества измененных файлов