Skip to content

Commit e08aca0

Browse files
✨ Property declaration improvement
1 parent 82360b0 commit e08aca0

File tree

3 files changed

+54
-7
lines changed

3 files changed

+54
-7
lines changed

SymfonyCustom/Sniffs/Classes/PropertyDeclarationSniff.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class PropertyDeclarationSniff implements Sniff
1717
*/
1818
public function register(): array
1919
{
20-
return [T_CLASS];
20+
return [T_CLASS, T_ANON_CLASS];
2121
}
2222

2323
/**
@@ -35,16 +35,26 @@ public function process(File $phpcsFile, $stackPtr): void
3535
$end = $tokens[$stackPtr]['scope_closer'];
3636
}
3737

38-
$scope = $phpcsFile->findNext(T_FUNCTION, $stackPtr, $end);
38+
$function = $phpcsFile->findNext(T_FUNCTION, $stackPtr, $end);
39+
if (false === $function) {
40+
return;
41+
}
3942

40-
$wantedTokens = [T_PUBLIC, T_PROTECTED, T_PRIVATE];
43+
$wantedTokens = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_ANON_CLASS];
44+
$scope = $phpcsFile->findNext($wantedTokens, $function + 1, $end);
4145

42-
while ($scope) {
43-
$scope = $phpcsFile->findNext($wantedTokens, $scope + 1, $end);
46+
while (false !== $scope) {
47+
if (T_ANON_CLASS === $tokens[$scope]['code']) {
48+
$scope = $tokens[$scope]['scope_closer'];
49+
50+
continue;
51+
}
4452

45-
if ($scope && T_VARIABLE === $tokens[$scope + 2]['code']) {
53+
if (T_VARIABLE === $tokens[$scope + 2]['code']) {
4654
$phpcsFile->addError('Declare class properties before methods', $scope, 'Invalid');
4755
}
56+
57+
$scope = $phpcsFile->findNext($wantedTokens, $scope + 1, $end);
4858
}
4959
}
5060
}

SymfonyCustom/Tests/Classes/PropertyDeclarationUnitTest.inc

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,39 @@ class ClassTest
88

99
private $property;
1010
}
11+
12+
class Bar
13+
{
14+
public function doStuff()
15+
{
16+
$var1 = 'foo';
17+
$var2 = 'bar';
18+
19+
$anonClass = new class($var1, $var2)
20+
{
21+
private $property;
22+
23+
public function thisIsAfterTheProperty()
24+
{
25+
}
26+
};
27+
}
28+
}
29+
30+
class MoreBar
31+
{
32+
public function doStuff()
33+
{
34+
$var1 = 'foo';
35+
$var2 = 'bar';
36+
37+
$anonClass = new class($var1, $var2)
38+
{
39+
public function thisShouldBeAfterTheProperty()
40+
{
41+
}
42+
43+
private $property;
44+
};
45+
}
46+
}

SymfonyCustom/Tests/Classes/PropertyDeclarationUnitTest.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ class PropertyDeclarationUnitTest extends AbstractSniffUnitTest
1717
protected function getErrorList(): array
1818
{
1919
return [
20-
9 => 1,
20+
9 => 1,
21+
43 => 1,
2122
];
2223
}
2324

0 commit comments

Comments
 (0)