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

Extract StatementIndentationFixer from BracesFixer

Julien Falque 3 лет назад
Родитель
Сommit
f65b48e75c

+ 5 - 0
doc/list.rst

@@ -2699,6 +2699,11 @@ List of Available Rules
    Part of rule sets `@PhpCsFixer <./ruleSets/PhpCsFixer.rst>`_ `@Symfony <./ruleSets/Symfony.rst>`_
 
    `Source PhpCsFixer\\Fixer\\Operator\\StandardizeNotEqualsFixer <./../src/Fixer/Operator/StandardizeNotEqualsFixer.php>`_
+-  `statement_indentation <./rules/whitespace/statement_indentation.rst>`_
+
+   Each statement must be indented.
+
+   `Source PhpCsFixer\\Fixer\\Whitespace\\StatementIndentationFixer <./../src/Fixer/Whitespace/StatementIndentationFixer.php>`_
 -  `static_lambda <./rules/function_notation/static_lambda.rst>`_
 
    Lambdas not (indirect) referencing ``$this`` must be declared ``static``.

+ 3 - 0
doc/rules/index.rst

@@ -825,6 +825,9 @@ Whitespace
 - `single_blank_line_at_eof <./whitespace/single_blank_line_at_eof.rst>`_
 
   A PHP file without end tag must always end with a single empty line feed.
+- `statement_indentation <./whitespace/statement_indentation.rst>`_
+
+  Each statement must be indented.
 - `types_spaces <./whitespace/types_spaces.rst>`_
 
   A single space or none should be around union type operator.

+ 25 - 0
doc/rules/whitespace/statement_indentation.rst

@@ -0,0 +1,25 @@
+==============================
+Rule ``statement_indentation``
+==============================
+
+Each statement must be indented.
+
+Examples
+--------
+
+Example #1
+~~~~~~~~~~
+
+.. code-block:: diff
+
+   --- Original
+   +++ New
+    <?php
+    if ($baz == true) {
+   -  echo "foo";
+   +    echo "foo";
+    }
+    else {
+   -      echo "bar";
+   +    echo "bar";
+    }

+ 1 - 1
src/Console/Command/FixCommand.php

@@ -194,7 +194,7 @@ Exit code of the fix command is built using following bit flags:
 * 64 - Exception raised within the application.
 
 EOF
-            ;
+        ;
     }
 
     /**

+ 3 - 1
src/Fixer/Basic/BracesFixer.php

@@ -18,6 +18,7 @@ use PhpCsFixer\AbstractProxyFixer;
 use PhpCsFixer\Fixer\ConfigurableFixerInterface;
 use PhpCsFixer\Fixer\ControlStructure\ControlStructureContinuationPositionFixer;
 use PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer;
+use PhpCsFixer\Fixer\Whitespace\StatementIndentationFixer;
 use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
 use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
 use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
@@ -136,7 +137,7 @@ class Foo
     /**
      * {@inheritdoc}
      *
-     * Must run before ArrayIndentationFixer, MethodArgumentSpaceFixer, MethodChainingIndentationFixer.
+     * Must run before ArrayIndentationFixer, MethodChainingIndentationFixer.
      * Must run after ClassAttributesSeparationFixer, ClassDefinitionFixer, ElseifFixer, EmptyLoopBodyFixer, LineEndingFixer, NoAlternativeSyntaxFixer, NoEmptyStatementFixer, NoUselessElseFixer, SingleLineThrowFixer, SingleSpaceAfterConstructFixer, SingleTraitInsertPerStatementFixer.
      */
     public function getPriority(): int
@@ -211,6 +212,7 @@ class Foo
         return [
             $this->getControlStructureContinuationPositionFixer(),
             new DeclareParenthesesFixer(),
+            new StatementIndentationFixer(true),
         ];
     }
 

+ 1 - 1
src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php

@@ -156,7 +156,7 @@ class Sample
     /**
      * {@inheritdoc}
      *
-     * Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer.
+     * Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer, StatementIndentationFixer.
      * Must run after OrderedClassElementsFixer, SingleClassElementPerStatementFixer.
      */
     public function getPriority(): int

+ 1 - 1
src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php

@@ -124,7 +124,7 @@ SAMPLE
      * {@inheritdoc}
      *
      * Must run before ArrayIndentationFixer.
-     * Must run after BracesFixer, CombineNestedDirnameFixer, FunctionDeclarationFixer, ImplodeCallFixer, MethodChainingIndentationFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUselessSprintfFixer, PowToExponentiationFixer, StrictParamFixer.
+     * Must run after CombineNestedDirnameFixer, FunctionDeclarationFixer, ImplodeCallFixer, MethodChainingIndentationFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUselessSprintfFixer, PowToExponentiationFixer, StrictParamFixer.
      */
     public function getPriority(): int
     {

+ 64 - 0
src/Fixer/Indentation.php

@@ -0,0 +1,64 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of PHP CS Fixer.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace PhpCsFixer\Fixer;
+
+use PhpCsFixer\Preg;
+use PhpCsFixer\Tokenizer\Tokens;
+
+/**
+ * @internal
+ */
+trait Indentation
+{
+    private function extractIndent(string $content): string
+    {
+        if (Preg::match('/\R(\h*)[^\r\n]*$/D', $content, $matches)) {
+            return $matches[1];
+        }
+
+        return '';
+    }
+
+    private function computeNewLineContent(Tokens $tokens, int $index): string
+    {
+        $content = $tokens[$index]->getContent();
+
+        if (0 !== $index && $tokens[$index - 1]->equalsAny([[T_OPEN_TAG], [T_CLOSE_TAG]])) {
+            $content = Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()).$content;
+        }
+
+        return $content;
+    }
+
+    private function isNewLineToken(Tokens $tokens, int $index): bool
+    {
+        $token = $tokens[$index];
+
+        if (
+            $token->isGivenKind(T_OPEN_TAG)
+            && isset($tokens[$index + 1])
+            && !$tokens[$index + 1]->isWhitespace()
+            && Preg::match('/\R/', $token->getContent())
+        ) {
+            return true;
+        }
+
+        if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML])) {
+            return false;
+        }
+
+        return (bool) Preg::match('/\R/', $this->computeNewLineContent($tokens, $index));
+    }
+}

+ 9 - 78
src/Fixer/Whitespace/ArrayIndentationFixer.php

@@ -15,6 +15,7 @@ declare(strict_types=1);
 namespace PhpCsFixer\Fixer\Whitespace;
 
 use PhpCsFixer\AbstractFixer;
+use PhpCsFixer\Fixer\Indentation;
 use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
 use PhpCsFixer\FixerDefinition\CodeSample;
 use PhpCsFixer\FixerDefinition\FixerDefinition;
@@ -26,11 +27,7 @@ use PhpCsFixer\Tokenizer\Tokens;
 
 final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
 {
-    /** @var int */
-    private $newlineTokenIndexCache;
-
-    /** @var int */
-    private $newlineTokenPositionCache;
+    use Indentation;
 
     /**
      * {@inheritdoc}
@@ -66,8 +63,7 @@ final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAw
 
     protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
     {
-        $this->returnWithUpdateCache(0, null);
-
+        $lastIndent = '';
         $scopes = [];
         $previousLineInitialIndent = '';
         $previousLineNewIndent = '';
@@ -91,12 +87,16 @@ final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAw
                 $scopes[] = [
                     'type' => 'array',
                     'end_index' => $endIndex,
-                    'initial_indent' => $this->getLineIndentation($tokens, $index),
+                    'initial_indent' => $lastIndent,
                 ];
 
                 continue;
             }
 
+            if ($this->isNewLineToken($tokens, $index)) {
+                $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index));
+            }
+
             if (null === $currentScope) {
                 continue;
             }
@@ -139,6 +139,7 @@ final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAw
                 }
 
                 $tokens[$index] = new Token([T_WHITESPACE, $content]);
+                $lastIndent = $this->extractIndent($content);
 
                 continue;
             }
@@ -199,74 +200,4 @@ final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAw
 
         return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex);
     }
-
-    private function getLineIndentation(Tokens $tokens, int $index): string
-    {
-        $newlineTokenIndex = $this->getPreviousNewlineTokenIndex($tokens, $index);
-
-        if (null === $newlineTokenIndex) {
-            return '';
-        }
-
-        return $this->extractIndent($this->computeNewLineContent($tokens, $newlineTokenIndex));
-    }
-
-    private function extractIndent(string $content): string
-    {
-        if (Preg::match('/\R(\h*)[^\r\n]*$/D', $content, $matches)) {
-            return $matches[1];
-        }
-
-        return '';
-    }
-
-    private function getPreviousNewlineTokenIndex(Tokens $tokens, int $startIndex): ?int
-    {
-        $index = $startIndex;
-        while ($index > 0) {
-            $index = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE], [T_INLINE_HTML]]);
-
-            if ($this->newlineTokenIndexCache > $index) {
-                return $this->returnWithUpdateCache($startIndex, $this->newlineTokenPositionCache);
-            }
-
-            if (null === $index) {
-                break;
-            }
-
-            if ($this->isNewLineToken($tokens, $index)) {
-                return $this->returnWithUpdateCache($startIndex, $index);
-            }
-        }
-
-        return $this->returnWithUpdateCache($startIndex, null);
-    }
-
-    private function isNewLineToken(Tokens $tokens, int $index): bool
-    {
-        if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML])) {
-            return false;
-        }
-
-        return (bool) Preg::match('/\R/', $this->computeNewLineContent($tokens, $index));
-    }
-
-    private function computeNewLineContent(Tokens $tokens, int $index): string
-    {
-        $content = $tokens[$index]->getContent();
-
-        if (0 !== $index && $tokens[$index - 1]->equalsAny([[T_OPEN_TAG], [T_CLOSE_TAG]])) {
-            $content = Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()).$content;
-        }
-
-        return $content;
-    }
-
-    private function returnWithUpdateCache(int $index, ?int $position): ?int
-    {
-        $this->newlineTokenIndexCache = $index;
-        $this->newlineTokenPositionCache = $position;
-
-        return $position;
-    }
 }

+ 10 - 0
src/Fixer/Whitespace/HeredocIndentationFixer.php

@@ -83,6 +83,16 @@ SAMPLE
         );
     }
 
+    /**
+     * {@inheritdoc}
+     *
+     * Must run after StatementIndentationFixer.
+     */
+    public function getPriority(): int
+    {
+        return -26;
+    }
+
     /**
      * {@inheritdoc}
      */

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