Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SingleLineCommentSpacingFixer - Introduction #6274

Merged
merged 1 commit into from Feb 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/list.rst
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions doc/ruleSets/Symfony.rst
Expand Up @@ -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']]``
Expand Down
34 changes: 34 additions & 0 deletions 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 changes: 3 additions & 0 deletions doc/rules/index.rst
Expand Up @@ -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.
Expand Down
119 changes: 119 additions & 0 deletions 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);
}
}
2 changes: 1 addition & 1 deletion src/Fixer/Phpdoc/PhpdocToCommentFixer.php
Expand Up @@ -49,7 +49,7 @@ public function isCandidate(Tokens $tokens): bool
/**
* {@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
Expand Down
1 change: 1 addition & 0 deletions src/RuleSet/Sets/SymfonySet.php
Expand Up @@ -158,6 +158,7 @@ public function getRules(): array
'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',
Expand Down
1 change: 1 addition & 0 deletions tests/AutoReview/FixerFactoryTest.php
Expand Up @@ -692,6 +692,7 @@ private static function getFixersPriorityGraph(): array
'phpdoc_to_comment' => [
'no_empty_comment',
'phpdoc_no_useless_inheritdoc',
'single_line_comment_spacing',
'single_line_comment_style',
],
'phpdoc_to_param_type' => [
Expand Down
144 changes: 144 additions & 0 deletions 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 {};
',
];
}
}
@@ -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;
2 changes: 1 addition & 1 deletion tests/Test/AbstractIntegrationCaseFactory.php
Expand Up @@ -66,7 +66,7 @@ public function create(SplFileInfo $file): IntegrationCase
);
} catch (\InvalidArgumentException $e) {
throw new \InvalidArgumentException(
sprintf('%s Test file: "%s".', $e->getMessage(), $file->getRelativePathname()),
sprintf('%s Test file: "%s".', $e->getMessage(), $file->getPathname()),
$e->getCode(),
$e
);
Expand Down