Skip to content

Commit 653cf88

Browse files
committed
NoLeadingImportSlashFixer - Add space if needed
1 parent 74666dc commit 653cf88

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/Fixer/Import/NoLeadingImportSlashFixer.php

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use PhpCsFixer\FixerDefinition\CodeSample;
1717
use PhpCsFixer\FixerDefinition\FixerDefinition;
1818
use PhpCsFixer\Tokenizer\CT;
19+
use PhpCsFixer\Tokenizer\Token;
1920
use PhpCsFixer\Tokenizer\Tokens;
2021
use PhpCsFixer\Tokenizer\TokensAnalyzer;
2122

@@ -65,13 +66,33 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens)
6566
$nextToken = $tokens[$nextTokenIdx];
6667

6768
if ($nextToken->isGivenKind(T_NS_SEPARATOR)) {
68-
$tokens->clearAt($nextTokenIdx);
69+
$this->removeLeadingImportSlash($tokens, $nextTokenIdx);
6970
} elseif ($nextToken->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) {
7071
$nextTokenIdx = $tokens->getNextMeaningfulToken($nextTokenIdx);
7172
if ($tokens[$nextTokenIdx]->isGivenKind(T_NS_SEPARATOR)) {
72-
$tokens->clearAt($nextTokenIdx);
73+
$this->removeLeadingImportSlash($tokens, $nextTokenIdx);
7374
}
7475
}
7576
}
7677
}
78+
79+
/**
80+
* @param Tokens $tokens
81+
* @param int $index
82+
*/
83+
private function removeLeadingImportSlash(Tokens $tokens, $index)
84+
{
85+
$previousIndex = $tokens->getPrevNonWhitespace($index);
86+
87+
if (
88+
$previousIndex < $index - 1
89+
|| $tokens[$previousIndex]->isComment()
90+
) {
91+
$tokens->clearAt($index);
92+
93+
return;
94+
}
95+
96+
$tokens[$index] = new Token([T_WHITESPACE, ' ']);
97+
}
7798
}

tests/Fixer/Import/NoLeadingImportSlashFixerTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ public function provideFixCases()
5353
use/*1*/\A\B;
5454
',
5555
],
56+
[
57+
'<?php use /*1*/A\B;',
58+
'<?php use\/*1*/A\B;',
59+
],
5660
[
5761
'<?php
5862
$a = function(\B\C $a) use ($b){
@@ -187,6 +191,16 @@ class Bar {
187191
use const \d\e;
188192
',
189193
],
194+
'no space case' => [
195+
'<?php
196+
use Events\Payment\Base as PaymentEvent;
197+
use const d\e;
198+
',
199+
'<?php
200+
use\Events\Payment\Base as PaymentEvent;
201+
use const\d\e;
202+
',
203+
],
190204
];
191205
}
192206

0 commit comments

Comments
 (0)