forked from symplify/coding-standard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChainMethodCallAnalyzer.php
More file actions
108 lines (85 loc) · 2.64 KB
/
ChainMethodCallAnalyzer.php
File metadata and controls
108 lines (85 loc) · 2.64 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
declare(strict_types=1);
namespace Symplify\CodingStandard\TokenAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class ChainMethodCallAnalyzer
{
private int $bracketNesting = 0;
public function __construct(
private readonly NewlineAnalyzer $newlineAnalyzer
) {
}
/**
* Matches e.g: return app()->some(), app()->some(), (clone app)->some()
*
* @param Tokens<Token> $tokens
*/
public function isPrecededByFuncCall(Tokens $tokens, int $position): bool
{
for ($i = $position; $i >= 0; --$i) {
/** @var Token $currentToken */
$currentToken = $tokens[$i];
if ($currentToken->getContent() === 'clone') {
return true;
}
if ($currentToken->getContent() === '(') {
return $this->newlineAnalyzer->doesContentBeforeBracketRequireNewline($tokens, $i);
}
if ($this->newlineAnalyzer->isNewlineToken($currentToken)) {
return false;
}
}
return false;
}
/**
* Matches e.g. someMethod($this->some()->method()), [$this->some()->method()]
*
* @param Tokens<Token> $tokens
*/
public function isPartOfMethodCallOrArray(Tokens $tokens, int $position): bool
{
$this->bracketNesting = 0;
for ($i = $position; $i >= 0; --$i) {
/** @var Token $currentToken */
$currentToken = $tokens[$i];
// break
if ($this->newlineAnalyzer->isNewlineToken($currentToken)) {
return false;
}
if ($this->isBreakingChar($currentToken)) {
return true;
}
if ($this->shouldBreakOnBracket($currentToken)) {
return true;
}
}
return false;
}
private function isBreakingChar(Token $currentToken): bool
{
if ($currentToken->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_OPEN, T_ARRAY, T_DOUBLE_COLON])) {
return true;
}
if ($currentToken->getContent() === '[') {
return true;
}
return $currentToken->getContent() === '.';
}
private function shouldBreakOnBracket(Token $token): bool
{
if ($token->getContent() === ')') {
--$this->bracketNesting;
return false;
}
if ($token->getContent() === '(') {
if ($this->bracketNesting !== 0) {
++$this->bracketNesting;
return false;
}
return true;
}
return false;
}
}