Skip to content

Commit dafb7ca

Browse files
committed
Improved PhpcsHelpers::variableIsProperty()
1 parent 6db6799 commit dafb7ca

File tree

1 file changed

+34
-13
lines changed

1 file changed

+34
-13
lines changed

Inpsyde/PhpcsHelpers.php

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -74,25 +74,46 @@ public static function classPropertiesTokenIndexes(
7474
*/
7575
public static function variableIsProperty(File $file, int $position): bool
7676
{
77-
$token = $file->getTokens()[$position];
77+
$tokens = $file->getTokens();
78+
$token = $tokens[$position];
7879
if ($token['code'] !== T_VARIABLE) {
7980
return false;
8081
}
8182

82-
$propertyPointer = $file->findPrevious(
83-
[T_STATIC, T_WHITESPACE, T_COMMENT],
84-
$position - 1,
85-
null,
86-
true
87-
);
83+
$classes = [T_CLASS, T_ANON_CLASS, T_TRAIT];
8884

89-
$propertyPointerToken = $file->getTokens()[$propertyPointer] ?? [];
85+
$classPointer = $file->findPrevious($classes, $position - 1);
86+
if (!$classPointer
87+
|| !array_key_exists($classPointer, $tokens)
88+
|| !in_array($tokens[$classPointer]['code'], $classes, true)
89+
) {
90+
return false;
91+
}
9092

91-
return in_array(
92-
($propertyPointerToken['code'] ?? ''),
93-
[T_PRIVATE, T_PROTECTED, T_PUBLIC, T_VAR],
94-
true
95-
);
93+
$opener = $tokens[$classPointer]['scope_opener'] ?? -1;
94+
$closer = $tokens[$classPointer]['scope_closer'] ?? -1;
95+
96+
if ($opener <= 0
97+
|| $closer <= 0
98+
|| $closer <= $opener
99+
|| $closer <= $position
100+
|| $opener >= $position
101+
) {
102+
return false;
103+
}
104+
105+
$exclude = Tokens::$emptyTokens;
106+
$exclude[] = T_STATIC;
107+
$propertyModifierPointer = $file->findPrevious($exclude, $position - 1, null, true);
108+
if (!$propertyModifierPointer || !array_key_exists($propertyModifierPointer, $tokens)) {
109+
return false;
110+
}
111+
112+
$propertyModifierCode = $tokens[$propertyModifierPointer]['code'] ?? '';
113+
$modifiers = Tokens::$scopeModifiers;
114+
$modifiers[] = T_VAR;
115+
116+
return in_array($propertyModifierCode, $modifiers, true);
96117
}
97118

98119
/**

0 commit comments

Comments
 (0)