Skip to content

Commit d027abb

Browse files
committed
Simplify and improve OOP scope check for nested functions
1 parent 07c94c7 commit d027abb

File tree

3 files changed

+18
-20
lines changed

3 files changed

+18
-20
lines changed

src/Standards/Squiz/Sniffs/PHP/InnerFunctionsSniff.php

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
use PHP_CodeSniffer\Files\File;
1313
use PHP_CodeSniffer\Sniffs\Sniff;
14+
use PHP_CodeSniffer\Util\Tokens;
1415

1516
class InnerFunctionsSniff implements Sniff
1617
{
@@ -45,39 +46,26 @@ public function process(File $phpcsFile, $stackPtr)
4546
return;
4647
}
4748

48-
$conditions = $tokens[$stackPtr]['conditions'];
49+
$reversedConditions = array_reverse($tokens[$stackPtr]['conditions'], true);
4950

5051
$outerFuncToken = null;
51-
foreach ($conditions as $condToken => $condition) {
52+
foreach ($reversedConditions as $condToken => $condition) {
5253
if ($condition === T_FUNCTION || $condition === T_CLOSURE) {
5354
$outerFuncToken = $condToken;
5455
break;
5556
}
57+
58+
if (\array_key_exists($condition, Tokens::$ooScopeTokens) === true) {
59+
// Ignore methods in OOP structures defined within functions.
60+
return;
61+
}
5662
}
5763

5864
if ($outerFuncToken === null) {
5965
// Not a nested function.
6066
return;
6167
}
6268

63-
$reversedConditions = array_reverse($conditions, true);
64-
$allowedOOPConditions = [
65-
T_ANON_CLASS => true,
66-
T_CLASS => true,
67-
T_TRAIT => true,
68-
T_INTERFACE => true,
69-
];
70-
foreach ($reversedConditions as $condToken => $condition) {
71-
if ($condToken <= $outerFuncToken) {
72-
break;
73-
}
74-
75-
if (\array_key_exists($condition, $allowedOOPConditions) === true) {
76-
// Ignore methods in OOP structures defined within functions.
77-
return;
78-
}
79-
}
80-
8169
$error = 'The use of inner functions is forbidden';
8270
$phpcsFile->addError($error, $stackPtr, 'NotAllowed');
8371

src/Standards/Squiz/Tests/PHP/InnerFunctionsUnitTest.inc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,13 @@ function foo() {
7575
function foo();
7676
}
7777
}
78+
79+
// But disallow functions nested inside those methods
80+
if (class_exists('NestedFunctionInMethod') === false) {
81+
class NestedFunctionInMethod {
82+
function foo() {
83+
function innerFunction() {}
84+
}
85+
}
86+
}
7887
}

src/Standards/Squiz/Tests/PHP/InnerFunctionsUnitTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public function getErrorList()
2929
5 => 1,
3030
46 => 1,
3131
55 => 1,
32+
83 => 1,
3233
];
3334

3435
}//end getErrorList()

0 commit comments

Comments
 (0)