Skip to content

Commit

Permalink
feature #5751 Extract DeclareParenthesesFixer from BracesFixer (julie…
Browse files Browse the repository at this point in the history
…nfalque, keradus)

This PR was merged into the master branch.

Discussion
----------

Extract DeclareParenthesesFixer from BracesFixer

Extracted from #4884.

Commits
-------

d2fd18b DX: rename DeclareBracesFixer to DeclareParenthesesFixer
a2f9c23 Extract DeclareBracesFixer from BracesFixer
  • Loading branch information
keradus committed Aug 29, 2021
2 parents 5799bac + d2fd18b commit 3f2a49e
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 35 deletions.
2 changes: 2 additions & 0 deletions doc/rules/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,8 @@ Language Construct
Calling ``unset`` on multiple items should be done in one call.
- `declare_equal_normalize <./language_construct/declare_equal_normalize.rst>`_
Equal sign in declare statement should be surrounded by spaces or not following configuration.
- `declare_parentheses <./language_construct/declare_parentheses.rst>`_
There must not be spaces around ``declare`` statement parentheses.
- `dir_constant <./language_construct/dir_constant.rst>`_ *(risky)*
Replaces ``dirname(__FILE__)`` expression with equivalent ``__DIR__`` constant.
- `error_suppression <./language_construct/error_suppression.rst>`_ *(risky)*
Expand Down
18 changes: 18 additions & 0 deletions doc/rules/language_construct/declare_parentheses.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
============================
Rule ``declare_parentheses``
============================

There must not be spaces around ``declare`` statement parentheses.

Examples
--------

Example #1
~~~~~~~~~~

.. code-block:: diff
--- Original
+++ New
-<?php declare ( strict_types=1 );
+<?php declare(strict_types=1);
51 changes: 16 additions & 35 deletions src/Fixer/Basic/BracesFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@

namespace PhpCsFixer\Fixer\Basic;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
Expand All @@ -35,7 +36,7 @@
*
* @author Dariusz Rumiński <[email protected]>
*/
final class BracesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
final class BracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/**
* @internal
Expand Down Expand Up @@ -156,6 +157,8 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
$this->fixControlContinuationBraces($tokens);
$this->fixSpaceAroundToken($tokens);
$this->fixDoWhile($tokens);

parent::applyFix($file, $tokens);
}

/**
Expand Down Expand Up @@ -187,6 +190,13 @@ protected function createConfigurationDefinition(): FixerConfigurationResolverIn
]);
}

protected function createProxyFixers(): array
{
return [
new DeclareParenthesesFixer(),
];
}

private function fixCommentBeforeBrace(Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
Expand Down Expand Up @@ -697,8 +707,10 @@ private function fixSpaceAroundToken(Tokens $tokens): void

// Declare tokens don't follow the same rules are other control statements
if ($token->isGivenKind(T_DECLARE)) {
$this->fixDeclareStatement($tokens, $index);
} elseif ($token->isGivenKind($controlTokens) || $token->isGivenKind(CT::T_USE_LAMBDA)) {
continue; // delegated to DeclareParenthesesFixer
}

if ($token->isGivenKind($controlTokens) || $token->isGivenKind(CT::T_USE_LAMBDA)) {
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index);

if (!$tokens[$nextNonWhitespaceIndex]->equals(':')) {
Expand Down Expand Up @@ -869,37 +881,6 @@ private function getFinalControlContinuationTokensForOpeningToken(int $openingTo
return [];
}

private function fixDeclareStatement(Tokens $tokens, int $index): void
{
$tokens->removeTrailingWhitespace($index);

$startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']);
$tokens->removeTrailingWhitespace($startParenthesisIndex);

$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$tokens->removeLeadingWhitespace($endParenthesisIndex);

$startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{']);
$startBraceToken = $tokens[$startBraceIndex];

if ($startBraceToken->equals('{')) {
$this->fixSingleLineWhitespaceForDeclare($tokens, $startBraceIndex);
}
}

private function fixSingleLineWhitespaceForDeclare(Tokens $tokens, int $startBraceIndex): void
{
// fix single-line whitespace before {
// eg: `declare(ticks=1){` => `declare(ticks=1) {`
// eg: `declare(ticks=1) {` => `declare(ticks=1) {`
if (
!$tokens[$startBraceIndex - 1]->isWhitespace()
|| $tokens[$startBraceIndex - 1]->isWhitespace(" \t")
) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
}
}

private function ensureWhitespaceAtIndexAndIndentMultilineComment(Tokens $tokens, int $index, string $whitespace): void
{
if ($tokens[$index]->isWhitespace()) {
Expand Down
56 changes: 56 additions & 0 deletions src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <[email protected]>
* Dariusz Rumiński <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace PhpCsFixer\Fixer\LanguageConstruct;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;

final class DeclareParenthesesFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must not be spaces around `declare` statement parentheses.',
[new CodeSample("<?php declare ( strict_types=1 );\n")]
);
}

public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(T_DECLARE);
}

protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];

if (!$token->isGivenKind(T_DECLARE)) {
continue;
}

$tokens->removeTrailingWhitespace($index);

$startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']);
$tokens->removeTrailingWhitespace($startParenthesisIndex);

$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$tokens->removeLeadingWhitespace($endParenthesisIndex);
}
}
}
57 changes: 57 additions & 0 deletions tests/Fixer/LanguageConstruct/DeclareParenthesesFixerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <[email protected]>
* Dariusz Rumiński <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace PhpCsFixer\Tests\Fixer\LanguageConstruct;

use PhpCsFixer\Tests\Test\AbstractFixerTestCase;

/**
* @internal
*
* @covers \PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer
*/
final class DeclareParenthesesFixerTest extends AbstractFixerTestCase
{
/**
* @dataProvider provideFixCases
*/
public function testFix(string $expected, ?string $input = null): void
{
$this->doTest($expected, $input);
}

public function provideFixCases()
{
yield 'spaces around parentheses' => [
'<?php declare(strict_types = 1);',
'<?php declare ( strict_types = 1 );',
];

yield 'newlines (\n) around parentheses' => [
'<?php declare(strict_types = 1);',
'<?php declare
(
strict_types = 1
);',
];

yield 'newlines (\r\n) around parentheses' => [
'<?php declare(strict_types = 1);',
"<?php declare\r
(\r
strict_types = 1\r
);",
];
}
}

0 comments on commit 3f2a49e

Please sign in to comment.