Skip to content

Commit 2b5a5a2

Browse files
committed
ReferenceUsedNamesOnlySniff: fixed fixer for reference via FQN without namespace in doccomment
1 parent 0ba2d4e commit 2b5a5a2

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

SlevomatCodingStandard/Sniffs/Namespaces/ReferenceUsedNamesOnlySniff.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,17 @@ public function process(\PHP_CodeSniffer\Files\File $phpcsFile, $openTagPointer)
271271
), $startPointer, self::CODE_REFERENCE_VIA_FULLY_QUALIFIED_NAME_WITHOUT_NAMESPACE);
272272
if ($fix) {
273273
$phpcsFile->fixer->beginChangeset();
274-
$phpcsFile->fixer->replaceToken($startPointer, substr($tokens[$startPointer]['content'], 1));
274+
275+
if ($reference->fromDocComment) {
276+
$fixedDocComment = preg_replace_callback('~(\\s|\|)(' . preg_quote($name, '~') . ')(\\s|\||\[|$)~', function (array $matches): string {
277+
return $matches[1] . ltrim($matches[2], '\\\\') . $matches[3];
278+
}, $tokens[$startPointer]['content']);
279+
280+
$phpcsFile->fixer->replaceToken($startPointer, $fixedDocComment);
281+
} else {
282+
$phpcsFile->fixer->replaceToken($startPointer, substr($tokens[$startPointer]['content'], 1));
283+
}
284+
275285
$phpcsFile->fixer->endChangeset();
276286
}
277287
} else {

tests/Sniffs/Namespaces/ReferenceUsedNamesOnlySniffTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,7 @@ public function testFixableReferenceViaFullyQualifiedNameWithoutNamespace(): voi
682682
'specialExceptionNames' => [
683683
'BarErrorX',
684684
],
685+
'searchAnnotations' => true,
685686
], [ReferenceUsedNamesOnlySniff::CODE_REFERENCE_VIA_FULLY_QUALIFIED_NAME_WITHOUT_NAMESPACE]);
686687
self::assertAllFixedInFile($report);
687688
}

tests/Sniffs/Namespaces/data/fixableReferenceViaFullyQualifiedNameWithoutNamespace.fixed.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
<?php
22

3+
/**
4+
* @param \Some\Exception $e
5+
* @throws \Exception
6+
*/
37
function bar(\Some\Exception $e)
48
{
59
try {
@@ -13,7 +17,7 @@ function bar(\Some\Exception $e)
1317
} catch (TypeError $ex) {
1418

1519
} catch (BarErrorX $ex) {
16-
20+
throw new Exception();
1721
}
1822
}
1923

tests/Sniffs/Namespaces/data/fixableReferenceViaFullyQualifiedNameWithoutNamespace.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
<?php
22

3+
/**
4+
* @param \Some\Exception $e
5+
* @throws \Exception
6+
*/
37
function bar(\Some\Exception $e)
48
{
59
try {
@@ -13,7 +17,7 @@ function bar(\Some\Exception $e)
1317
} catch (\TypeError $ex) {
1418

1519
} catch (\BarErrorX $ex) {
16-
20+
throw new \Exception();
1721
}
1822
}
1923

0 commit comments

Comments
 (0)