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

FixerInterface::configure(null) reset fixer to use default configuration

Dariusz Ruminski 8 лет назад
Родитель
Сommit
97e688bc54

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

@@ -31,6 +31,8 @@ final class Psr0Fixer extends AbstractPsrAutoloadingFixer
     public function configure(array $configuration = null)
     {
         if (null === $configuration) {
+            $this->configuration = array();
+
             return;
         }
 

+ 4 - 1
src/Fixer/ClassNotation/VisibilityRequiredFixer.php

@@ -27,7 +27,8 @@ use PhpCsFixer\Tokenizer\TokensAnalyzer;
 final class VisibilityRequiredFixer extends AbstractFixer
 {
     private $options = array('property', 'method', 'const');
-    private $configuration = array('property', 'method');
+    private static $defaultConfiguration = array('property', 'method');
+    private $configuration;
 
     /**
      * Any of the class elements 'property', 'method' or 'const' can be configured.
@@ -40,6 +41,8 @@ final class VisibilityRequiredFixer extends AbstractFixer
     public function configure(array $configuration = null)
     {
         if (null === $configuration) {
+            $this->configuration = self::$defaultConfiguration;
+
             return;
         }
 

+ 10 - 5
src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php

@@ -23,11 +23,9 @@ use PhpCsFixer\Tokenizer\Tokens;
 final class NoUnneededControlParenthesesFixer extends AbstractFixer
 {
     /**
-     * To be removed when PHP support will be 5.5+.
-     *
-     * @var string[] List of statements to fix
+     * @var string[]
      */
-    private $controlStatements = array(
+    private static $defaultConfiguration = array(
         'break',
         'clone',
         'continue',
@@ -37,6 +35,11 @@ final class NoUnneededControlParenthesesFixer extends AbstractFixer
         'yield',
     );
 
+    /**
+     * @var string[] List of statements to fix
+     */
+    private $controlStatements;
+
     private static $loops = array(
         'break' => array('lookupTokens' => T_BREAK, 'neededSuccessors' => array(';')),
         'clone' => array('lookupTokens' => T_CLONE, 'neededSuccessors' => array(';', ':', ',', ')'), 'forbiddenContents' => array('?', ':')),
@@ -53,7 +56,7 @@ final class NoUnneededControlParenthesesFixer extends AbstractFixer
     {
         parent::__construct();
 
-        // To be moved back on static when PHP support will be 5.5+
+        // To be moved back to compile time property declaration when PHP support of PHP CS Fixer will be 5.5+
         if (defined('T_YIELD')) {
             self::$loops['yield'] = array('lookupTokens' => T_YIELD, 'neededSuccessors' => array(';', ')'));
         }
@@ -65,6 +68,8 @@ final class NoUnneededControlParenthesesFixer extends AbstractFixer
     public function configure(array $controlStatements = null)
     {
         if (null === $controlStatements) {
+            $this->controlStatements = self::$defaultConfiguration;
+
             return;
         }
 

+ 11 - 1
src/Fixer/PhpUnit/PhpUnitConstructFixer.php

@@ -21,13 +21,21 @@ use PhpCsFixer\Tokenizer\Tokens;
  */
 final class PhpUnitConstructFixer extends AbstractFixer
 {
-    private $configuration = array(
+    /**
+     * @var string[]
+     */
+    private static $defaultConfiguration = array(
         'assertSame',
         'assertEquals',
         'assertNotEquals',
         'assertNotSame',
     );
 
+    /**
+     * @var string[]
+     */
+    private $configuration;
+
     private $assertionFixers = array(
         'assertSame' => 'fixAssertPositive',
         'assertEquals' => 'fixAssertPositive',
@@ -41,6 +49,8 @@ final class PhpUnitConstructFixer extends AbstractFixer
     public function configure(array $usingMethods = null)
     {
         if (null === $usingMethods) {
+            $this->configuration = self::$defaultConfiguration;
+
             return;
         }
 

+ 11 - 1
src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php

@@ -46,7 +46,10 @@ final class PhpUnitDedicateAssertFixer extends AbstractFixer
         'is_string' => true,
     );
 
-    private $configuration = array(
+    /**
+     * @var string[]
+     */
+    private static $defaultConfiguration = array(
         'array_key_exists',
         'empty',
         'file_exists',
@@ -70,12 +73,19 @@ final class PhpUnitDedicateAssertFixer extends AbstractFixer
         'is_string',
     );
 
+    /**
+     * @var string[]
+     */
+    private $configuration;
+
     /**
      * @param array|null $configuration
      */
     public function configure(array $configuration = null)
     {
         if (null === $configuration) {
+            $this->configuration = self::$defaultConfiguration;
+
             return;
         }
 

+ 11 - 1
src/Fixer/PhpUnit/PhpUnitStrictFixer.php

@@ -21,13 +21,21 @@ use PhpCsFixer\Tokenizer\Tokens;
  */
 final class PhpUnitStrictFixer extends AbstractFixer
 {
-    private $configuration = array(
+    /**
+     * @var string[]
+     */
+    private static $defaultConfiguration = array(
         'assertAttributeEquals',
         'assertAttributeNotEquals',
         'assertEquals',
         'assertNotEquals',
     );
 
+    /**
+     * @var string[]
+     */
+    private $configuration;
+
     private $assertionMap = array(
         'assertAttributeEquals' => 'assertAttributeSame',
         'assertAttributeNotEquals' => 'assertAttributeNotSame',
@@ -41,6 +49,8 @@ final class PhpUnitStrictFixer extends AbstractFixer
     public function configure(array $usingMethods = null)
     {
         if (null === $usingMethods) {
+            $this->configuration = self::$defaultConfiguration;
+
             return;
         }
 

+ 15 - 2
src/Fixer/Whitespace/NoExtraConsecutiveBlankLinesFixer.php

@@ -29,12 +29,22 @@ final class NoExtraConsecutiveBlankLinesFixer extends AbstractFixer implements W
     /**
      * @var array<int, string> key is token id, value is name of callback
      */
-    private $tokenKindCallbackMap = array(T_WHITESPACE => 'removeMultipleBlankLines');
+    private static $defaultTokenKindCallbackMap = array(T_WHITESPACE => 'removeMultipleBlankLines');
 
     /**
      * @var array<string, string> token prototype, value is name of callback
      */
-    private $tokenEqualsMap = array();
+    private static $defaultTokenEqualsMap = array();
+
+    /**
+     * @var array<int, string> key is token id, value is name of callback
+     */
+    private $tokenKindCallbackMap;
+
+    /**
+     * @var array<string, string> token prototype, value is name of callback
+     */
+    private $tokenEqualsMap;
 
     /**
      * @var Tokens
@@ -66,6 +76,9 @@ final class NoExtraConsecutiveBlankLinesFixer extends AbstractFixer implements W
     public function configure(array $configuration = null)
     {
         if (null === $configuration) {
+            $this->tokenKindCallbackMap = self::$defaultTokenKindCallbackMap;
+            $this->tokenEqualsMap = self::$defaultTokenEqualsMap;
+
             return;
         }
 

+ 2 - 0
src/FixerInterface.php

@@ -23,6 +23,8 @@ interface FixerInterface
      * Set configuration.
      *
      * New configuration must override current one, not patch it.
+     * Using `null` makes fixer to use default configuration (or reset configuration from previously configured back
+     * to default one).
      *
      * Some fixers may have no configuration, then - simply pass null.
      * Other ones may have configuration that will change behavior of fixer,

+ 79 - 42
src/Test/AbstractFixerTestCase.php

@@ -20,6 +20,7 @@ use PhpCsFixer\RuleSet;
 use PhpCsFixer\Tokenizer\Token;
 use PhpCsFixer\Tokenizer\Tokens;
 use PhpCsFixer\Utils;
+use PhpCsFixer\WhitespacesFixerConfig;
 use Prophecy\Argument;
 
 /**
@@ -33,53 +34,50 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
     protected $linter;
 
     /**
-     * @var FixerInterface|null
+     * @var null|FixerInterface
      */
-    private $fixer;
-
-    public function setUp()
-    {
-        $this->linter = $this->getLinter();
-    }
+    protected $fixer;
 
     /**
-     * Create fixer factory with all needed fixers registered.
-     *
-     * @return FixerFactory
+     * @var null|string
      */
-    protected function createFixerFactory()
+    private $fixerClassName;
+
+    public function setUp()
     {
-        return FixerFactory::create()->registerBuiltInFixers();
+        $this->linter = $this->getLinter();
+        $this->fixer = $this->createFixer();
     }
 
     /**
      * @return FixerInterface
      */
-    protected function getFixer()
+    protected function createFixer()
     {
-        if (null !== $this->fixer) {
-            return $this->fixer;
-        }
-
-        $name = $this->getFixerName();
-        $configuration = $this->getFixerConfiguration();
+        $fixerClassName = $this->getFixerClassName();
+        $fixer = new $fixerClassName();
 
-        try {
-            $fixers = $this->createFixerFactory()
-                ->useRuleSet(new RuleSet(array($name => $configuration)))
-                ->getFixers()
-            ;
-        } catch (\UnexpectedValueException $e) {
-            throw new \UnexpectedValueException('Cannot determine fixer class, perhaps you forget to override `getFixerName` or `createFixerFactory` method?');
-        }
+        $fixer->configure(
+            is_array($this->getFixerConfiguration())
+                ? $this->getFixerConfiguration()
+                : null
+        );
 
-        if (1 !== count($fixers)) {
-            throw new \UnexpectedValueException(sprintf('Determine fixer class should result in one fixer, got "%d". Perhaps you configured the fixer to "false" ?', count($fixers)));
+        if ($fixer instanceof WhitespacesFixerConfigAwareInterface) {
+            $fixer->setWhitespacesConfig($this->getDefaultWhitespacesFixerConfig());
         }
 
-        $this->fixer = $fixers[0];
+        return $fixer;
+    }
 
-        return $this->fixer;
+    /**
+     * Create fixer factory with all needed fixers registered.
+     *
+     * @return FixerFactory
+     */
+    protected function createFixerFactory()
+    {
+        return FixerFactory::create()->registerBuiltInFixers();
     }
 
     /**
@@ -128,20 +126,18 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
      * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
      * not test anything.
      *
-     * @param string              $expected The expected fixer output
-     * @param string|null         $input    The fixer input, or null if it should intentionally be equal to the output
-     * @param \SplFileInfo|null   $file     The file to fix, or null if unneeded
-     * @param FixerInterface|null $fixer    The fixer to be used, or null if it should be inferred from the test name
+     * @param string            $expected The expected fixer output
+     * @param string|null       $input    The fixer input, or null if it should intentionally be equal to the output
+     * @param \SplFileInfo|null $file     The file to fix, or null if unneeded
      */
-    protected function doTest($expected, $input = null, \SplFileInfo $file = null, FixerInterface $fixer = null)
+    protected function doTest($expected, $input = null, \SplFileInfo $file = null)
     {
         if ($expected === $input) {
             throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
         }
 
-        $fixer = $fixer ?: $this->getFixer();
         $file = $file ?: $this->getTestFile();
-        $fileIsSupported = $fixer->supports($file);
+        $fileIsSupported = $this->fixer->supports($file);
 
         if (null !== $input) {
             $this->assertNull($this->lintSource($input));
@@ -150,8 +146,8 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
             $tokens = Tokens::fromCode($input);
 
             if ($fileIsSupported) {
-                $this->assertTrue($fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
-                $fixResult = $fixer->fix($file, $tokens);
+                $this->assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
+                $fixResult = $this->fixer->fix($file, $tokens);
                 $this->assertNull($fixResult, '->fix method must return null.');
             }
 
@@ -178,7 +174,7 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
         Tokens::clearCache();
         $tokens = Tokens::fromCode($expected);
 
-        $isCandidate = $fixer->isCandidate($tokens);
+        $isCandidate = $this->fixer->isCandidate($tokens);
         $this->assertFalse($tokens->isChanged(), 'Fixer should not touch Tokens on candidate check.');
 
         if (!$isCandidate) {
@@ -186,7 +182,7 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
         }
 
         if ($fileIsSupported) {
-            $fixResult = $fixer->fix($file, $tokens);
+            $fixResult = $this->fixer->fix($file, $tokens);
             $this->assertNull($fixResult, '->fix method must return null.');
         }
 
@@ -253,4 +249,45 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
 
         return $linter;
     }
+
+    private function getDefaultWhitespacesFixerConfig()
+    {
+        static $defaultWhitespacesFixerConfig = null;
+
+        if (null === $defaultWhitespacesFixerConfig) {
+            $defaultWhitespacesFixerConfig = new WhitespacesFixerConfig('    ', "\n");
+        }
+
+        return $defaultWhitespacesFixerConfig;
+    }
+
+    /**
+     * @return string
+     */
+    private function getFixerClassName()
+    {
+        if (null !== $this->fixerClassName) {
+            return $this->fixerClassName;
+        }
+
+        $name = $this->getFixerName();
+        $configuration = $this->getFixerConfiguration();
+
+        try {
+            $fixers = $this->createFixerFactory()
+                ->useRuleSet(new RuleSet(array($name => $configuration)))
+                ->getFixers()
+            ;
+        } catch (\UnexpectedValueException $e) {
+            throw new \UnexpectedValueException('Cannot determine fixer class, perhaps you forget to override `getFixerName` or `createFixerFactory` method?');
+        }
+
+        if (1 !== count($fixers)) {
+            throw new \UnexpectedValueException(sprintf('Determine fixer class should result in one fixer, got "%d". Perhaps you configured the fixer to "false" ?', count($fixers)));
+        }
+
+        $this->fixerClassName = get_class($fixers[0]);
+
+        return $this->fixerClassName;
+    }
 }

+ 5 - 5
tests/Fixer/Alias/RandomApiMigrationFixerTest.php

@@ -27,7 +27,7 @@ final class RandomApiMigrationFixerTest extends AbstractFixerTestCase
      */
     public function testConfigureCheckSearchFunction()
     {
-        $this->getFixer()->configure(array('is_null' => 'random_int'));
+        $this->fixer->configure(array('is_null' => 'random_int'));
     }
 
     /**
@@ -36,16 +36,16 @@ final class RandomApiMigrationFixerTest extends AbstractFixerTestCase
      */
     public function testConfigureCheckReplacementType()
     {
-        $this->getFixer()->configure(array('rand' => null));
+        $this->fixer->configure(array('rand' => null));
     }
 
     public function testConfigure()
     {
         $config = array('rand' => 'random_int');
-        $this->getFixer()->configure($config);
+        $this->fixer->configure($config);
 
         /** @var $replacements string[] */
-        $replacements = static::getObjectAttribute($this->getFixer(), 'configuration');
+        $replacements = static::getObjectAttribute($this->fixer, 'configuration');
         static::assertSame(
             array('rand' => array('alternativeName' => 'random_int', 'argumentCount' => array(0, 2))),
             $replacements
@@ -57,7 +57,7 @@ final class RandomApiMigrationFixerTest extends AbstractFixerTestCase
      */
     public function testFix($expected, $input = null, array $config = null)
     {
-        $this->getFixer()->configure($config);
+        $this->fixer->configure($config);
 
         $this->doTest($expected, $input);
     }

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