Browse Source

SingleLineCommentSpacingFixer - Introduction

SpacePossum 3 years ago
parent
commit
701b30e6aa

+ 7 - 0
doc/list.rst

@@ -2625,6 +2625,13 @@ List of Available Rules
    Part of rule sets `@PSR12 <./ruleSets/PSR12.rst>`_ `@PSR2 <./ruleSets/PSR2.rst>`_ `@PhpCsFixer <./ruleSets/PhpCsFixer.rst>`_ `@Symfony <./ruleSets/Symfony.rst>`_
 
    `Source PhpCsFixer\\Fixer\\Import\\SingleLineAfterImportsFixer <./../src/Fixer/Import/SingleLineAfterImportsFixer.php>`_
+-  `single_line_comment_spacing <./rules/comment/single_line_comment_spacing.rst>`_
+
+   Single-line comments must have proper spacing.
+
+   Part of rule sets `@PhpCsFixer <./ruleSets/PhpCsFixer.rst>`_ `@Symfony <./ruleSets/Symfony.rst>`_
+
+   `Source PhpCsFixer\\Fixer\\Comment\\SingleLineCommentSpacingFixer <./../src/Fixer/Comment/SingleLineCommentSpacingFixer.php>`_
 -  `single_line_comment_style <./rules/comment/single_line_comment_style.rst>`_
 
    Single-line comments and multi-line comments with only one line of actual content should use the ``//`` syntax.

+ 1 - 0
doc/ruleSets/Symfony.rst

@@ -112,6 +112,7 @@ Rules
 - `protected_to_private <./../rules/class_notation/protected_to_private.rst>`_
 - `semicolon_after_instruction <./../rules/semicolon/semicolon_after_instruction.rst>`_
 - `single_class_element_per_statement <./../rules/class_notation/single_class_element_per_statement.rst>`_
+- `single_line_comment_spacing <./../rules/comment/single_line_comment_spacing.rst>`_
 - `single_line_comment_style <./../rules/comment/single_line_comment_style.rst>`_
   config:
   ``['comment_types' => ['hash']]``

+ 34 - 0
doc/rules/comment/single_line_comment_spacing.rst

@@ -0,0 +1,34 @@
+====================================
+Rule ``single_line_comment_spacing``
+====================================
+
+Single-line comments must have proper spacing.
+
+Examples
+--------
+
+Example #1
+~~~~~~~~~~
+
+.. code-block:: diff
+
+   --- Original
+   +++ New
+    <?php
+   -//comment 1
+   -#comment 2
+   -/*comment 3*/
+   +// comment 1
+   +# comment 2
+   +/* comment 3 */
+
+Rule sets
+---------
+
+The rule is part of the following rule sets:
+
+@PhpCsFixer
+  Using the `@PhpCsFixer <./../../ruleSets/PhpCsFixer.rst>`_ rule set will enable the ``single_line_comment_spacing`` rule.
+
+@Symfony
+  Using the `@Symfony <./../../ruleSets/Symfony.rst>`_ rule set will enable the ``single_line_comment_spacing`` rule.

+ 3 - 0
doc/rules/index.rst

@@ -219,6 +219,9 @@ Comment
 - `no_trailing_whitespace_in_comment <./comment/no_trailing_whitespace_in_comment.rst>`_
 
   There MUST be no trailing spaces inside comment or PHPDoc.
+- `single_line_comment_spacing <./comment/single_line_comment_spacing.rst>`_
+
+  Single-line comments must have proper spacing.
 - `single_line_comment_style <./comment/single_line_comment_style.rst>`_
 
   Single-line comments and multi-line comments with only one line of actual content should use the ``//`` syntax.

+ 119 - 0
src/Fixer/Comment/SingleLineCommentSpacingFixer.php

@@ -0,0 +1,119 @@
+<?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\Comment;
+
+use PhpCsFixer\AbstractFixer;
+use PhpCsFixer\FixerDefinition\CodeSample;
+use PhpCsFixer\FixerDefinition\FixerDefinition;
+use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
+use PhpCsFixer\Preg;
+use PhpCsFixer\Tokenizer\Token;
+use PhpCsFixer\Tokenizer\Tokens;
+
+final class SingleLineCommentSpacingFixer extends AbstractFixer
+{
+    /**
+     * {@inheritdoc}
+     */
+    public function getDefinition(): FixerDefinitionInterface
+    {
+        return new FixerDefinition(
+            'Single-line comments must have proper spacing.',
+            [
+                new CodeSample(
+                    '<?php
+//comment 1
+#comment 2
+/*comment 3*/
+'
+                ),
+            ]
+        );
+    }
+
+    /**
+     * {@inheritdoc}
+     *
+     * Must run after PhpdocToCommentFixer.
+     */
+    public function getPriority(): int
+    {
+        return 1;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function isCandidate(Tokens $tokens): bool
+    {
+        return $tokens->isTokenKindFound(T_COMMENT);
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
+    {
+        for ($index = \count($tokens) - 1; 0 <= $index; --$index) {
+            $token = $tokens[$index];
+
+            if (!$token->isGivenKind(T_COMMENT)) {
+                continue;
+            }
+
+            $content = $token->getContent();
+            $contentLength = \strlen($content);
+
+            if ('/' === $content[0]) {
+                if ($contentLength < 3) {
+                    continue; // cheap check for "//"
+                }
+
+                if ('*' === $content[1]) { // slash asterisk comment
+                    if ($contentLength < 5 || '*' === $content[2] || str_contains($content, "\n")) {
+                        continue; // cheap check for "/**/", comment that looks like a PHPDoc, or multi line comment
+                    }
+
+                    $newContent = rtrim(substr($content, 0, -2)).' '.substr($content, -2);
+                    $newContent = $this->fixCommentLeadingSpace($newContent, '/*');
+                } else { // double slash comment
+                    $newContent = $this->fixCommentLeadingSpace($content, '//');
+                }
+            } else { // hash comment
+                if ($contentLength < 2 || '[' === $content[1]) { // cheap check for "#" or annotation (like) comment
+                    continue;
+                }
+
+                $newContent = $this->fixCommentLeadingSpace($content, '#');
+            }
+
+            if ($newContent !== $content) {
+                $tokens[$index] = new Token([T_COMMENT, $newContent]);
+            }
+        }
+    }
+
+    // fix space between comment open and leading text
+    private function fixCommentLeadingSpace(string $content, string $prefix): string
+    {
+        if (0 !== Preg::match(sprintf('@^%s\h+.*$@', preg_quote($prefix, '@')), $content)) {
+            return $content;
+        }
+
+        $position = \strlen($prefix);
+
+        return substr($content, 0, $position).' '.substr($content, $position);
+    }
+}

+ 1 - 1
src/Fixer/Phpdoc/PhpdocToCommentFixer.php

@@ -49,7 +49,7 @@ final class PhpdocToCommentFixer extends AbstractFixer implements ConfigurableFi
     /**
      * {@inheritdoc}
      *
-     * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer, SingleLineCommentStyleFixer.
+     * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer, SingleLineCommentSpacingFixer, SingleLineCommentStyleFixer.
      * Must run after CommentToPhpdocFixer.
      */
     public function getPriority(): int

+ 1 - 0
src/RuleSet/Sets/SymfonySet.php

@@ -158,6 +158,7 @@ final class SymfonySet extends AbstractRuleSetDescription
             'protected_to_private' => true,
             'semicolon_after_instruction' => true,
             'single_class_element_per_statement' => true,
+            'single_line_comment_spacing' => true,
             'single_line_comment_style' => [
                 'comment_types' => [
                     'hash',

+ 1 - 0
tests/AutoReview/FixerFactoryTest.php

@@ -692,6 +692,7 @@ final class FixerFactoryTest extends TestCase
             'phpdoc_to_comment' => [
                 'no_empty_comment',
                 'phpdoc_no_useless_inheritdoc',
+                'single_line_comment_spacing',
                 'single_line_comment_style',
             ],
             'phpdoc_to_param_type' => [

+ 144 - 0
tests/Fixer/Comment/SingleLineCommentSpacingFixerTest.php

@@ -0,0 +1,144 @@
+<?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\Tests\Fixer\Comment;
+
+use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
+
+/**
+ * @internal
+ *
+ * @covers \PhpCsFixer\Fixer\Comment\SingleLineCommentSpacingFixer
+ */
+final class SingleLineCommentSpacingFixerTest extends AbstractFixerTestCase
+{
+    /**
+     * @dataProvider provideTestCases
+     */
+    public function testFix(string $expected, ?string $input = null): void
+    {
+        $this->doTest($expected, $input);
+    }
+
+    public function provideTestCases(): iterable
+    {
+        yield 'comment list' => [
+            '<?php
+                // following:
+                //     1 :
+                //     2 :
+
+                # Test:
+                #   - abc
+                #   - fgh
+
+                # Title:
+                #   | abc1
+                #   | xyz
+
+                // Point:
+                //  * first point
+                //  * some other point
+
+                // Matrix:
+                //   [1,2]
+                //   [3,4]
+            ',
+        ];
+
+        yield [
+            '<?php /*    XYZ */',
+            '<?php /*    XYZ   */',
+        ];
+
+        yield [
+            '<?php // /',
+            '<?php ///',
+        ];
+
+        yield [
+            '<?php // //',
+            '<?php ////',
+        ];
+
+        yield 'hash open slash asterisk close' => [
+            '<?php # A*/',
+            '<?php #A*/',
+        ];
+
+        yield [
+            "<?php
+// a
+# b
+/* ABC */
+
+//     \t d
+#\te
+/* f */
+",
+            "<?php
+//a
+#b
+/*ABC*/
+
+//     \t d
+#\te
+/* f     */
+",
+        ];
+
+        yield 'do not fix multi line comments' => [
+            '<?php
+/*
+*/
+
+/*A
+B*/
+',
+        ];
+
+        yield 'empty double slash' => [
+            '<?php //',
+        ];
+
+        yield 'empty hash' => [
+            '<?php #',
+        ];
+
+        yield [
+            '<?php /**/',
+        ];
+
+        yield [
+            '<?php /***/',
+        ];
+
+        yield 'do not fix PHPDocs' => [
+            "<?php /**\n*/ /**\nX1*/ /**  Y1  */",
+        ];
+
+        yield 'do not fix comments looking like PHPDocs' => [
+            '<?php /**/ /**X1*/ /**  Y1  */',
+        ];
+
+        yield 'do not fix annotation' => [
+            '<?php
+namespace PhpCsFixer\Tests\Fixer\Basic;
+new
+#[Foo]
+class extends stdClass {};
+',
+        ];
+    }
+}

+ 19 - 0
tests/Fixtures/Integration/priority/phpdoc_to_comment,single_line_comment_spacing.test

@@ -0,0 +1,19 @@
+--TEST--
+Integration of fixers: phpdoc_to_comment,single_line_comment_spacing.
+--RULESET--
+{"phpdoc_to_comment": true, "single_line_comment_spacing": true}
+--EXPECT--
+<?php
+
+$first = true;// needed because by default first docblock is never fixed.
+
+/* Test */
+echo 1;
+
+--INPUT--
+<?php
+
+$first = true;// needed because by default first docblock is never fixed.
+
+/** Test*/
+echo 1;

Some files were not shown because too many files changed in this diff