-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPropertyDollarSignSniff.php
81 lines (64 loc) · 2.12 KB
/
PropertyDollarSignSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Worksome\CodingStyle\Sniffs\PhpDoc;
use InvalidArgumentException;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use Worksome\CodingStyle\Sniffs\Support\PropertyDoc;
class PropertyDollarSignSniff implements Sniff
{
public function register(): array
{
return [
T_DOC_COMMENT_TAG,
];
}
public function process(File $phpcsFile, $stackPtr)
{
try {
$propertyDoc = PropertyDoc::from($this->getLineOfDocblock($phpcsFile, $stackPtr));
} catch (InvalidArgumentException) {
return;
}
if ($propertyDoc->variableHasDollarSymbol()) {
return;
}
$phpcsFile->addFixableError(
'All @property variables should start with a dollar symbol.',
$stackPtr,
self::class
);
if ($phpcsFile->fixer === null) {
return;
}
$this->replaceLineOfDocblock($phpcsFile, $stackPtr, " {$propertyDoc->joined()}" . PHP_EOL);
}
private function getLineOfDocblock(File $phpcsFile, int $startPtr): string
{
$currentPointer = $startPtr;
$content = '';
while (! str_ends_with($content, PHP_EOL)) {
if ($phpcsFile->numTokens === $currentPointer) {
continue;
}
$content .= $phpcsFile->getTokensAsString($currentPointer, 1);
$currentPointer += 1;
}
return trim($content);
}
private function replaceLineOfDocblock(File $phpcsFile, int $startPtr, string $newContent): void
{
$eolPointer = $startPtr;
$content = '';
do {
if ($phpcsFile->numTokens === $eolPointer) {
continue;
}
$eolPointer += 1;
$content = $phpcsFile->getTokensAsString($eolPointer, 1);
} while (! str_ends_with($content, PHP_EOL));
foreach (array_reverse(range($startPtr, $eolPointer)) as $ptrToDelete) {
$phpcsFile->fixer->replaceToken($ptrToDelete, '');
}
$phpcsFile->fixer->replaceToken($startPtr - 1, $newContent);
}
}