-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathInlineVariableDocBlockMalformWorker.php
More file actions
79 lines (64 loc) · 2.25 KB
/
Copy pathInlineVariableDocBlockMalformWorker.php
File metadata and controls
79 lines (64 loc) · 2.25 KB
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
<?php
declare(strict_types=1);
namespace Symplify\CodingStandard\TokenRunner\DocBlock\MalformWorker;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symplify\CodingStandard\TokenRunner\Contract\DocBlock\MalformWorkerInterface;
use Symplify\CodingStandard\Utils\Regex;
final class InlineVariableDocBlockMalformWorker implements MalformWorkerInterface
{
/**
* @see https://regex101.com/r/GkyV1C/1
*/
private const string SINGLE_ASTERISK_START_REGEX = '#^/\*\s+\*(\s+@(?:psalm-|phpstan-)?var)#';
/**
* @see https://regex101.com/r/9cfhFI/1
*/
private const string SPACE_REGEX = '#\s+#m';
/**
* @see https://regex101.com/r/VpTDCd/1
*/
private const string ASTERISK_LEFTOVERS_REGEX = '#(\*\*)(\s+\*)#';
/**
* @param Tokens<Token> $tokens
*/
public function work(string $docContent, Tokens $tokens, int $position): string
{
if (! $this->isVariableComment($tokens, $position)) {
return $docContent;
}
// more than 2 newlines - keep it
if (substr_count($docContent, "\n") > 2) {
return $docContent;
}
// asterisk start
$docContent = Regex::replace($docContent, self::SINGLE_ASTERISK_START_REGEX, '/**$1');
// inline
$docContent = Regex::replace($docContent, self::SPACE_REGEX, ' ');
// remove asterisk leftover
return Regex::replace($docContent, self::ASTERISK_LEFTOVERS_REGEX, '$1');
}
/**
* @param Tokens<Token> $tokens
*/
private function isVariableComment(Tokens $tokens, int $position): bool
{
$nextPosition = $tokens->getNextMeaningfulToken($position);
if ($nextPosition === null) {
return false;
}
$nextNextPosition = $tokens->getNextMeaningfulToken($nextPosition + 2);
if ($nextNextPosition === null) {
return false;
}
/** @var Token $nextNextToken */
$nextNextToken = $tokens[$nextNextPosition];
if ($nextNextToken->isGivenKind([T_STATIC, T_FUNCTION])) {
return false;
}
// is inline variable
/** @var Token $nextToken */
$nextToken = $tokens[$nextPosition];
return $nextToken->isGivenKind(T_VARIABLE);
}
}