Skip to content

Commit 1983715

Browse files
committed
FunctionDeclarations::getProperties(): has_body determination - efficiency fix + bug fix
No need to walk the same set of tokens twice to determine whether a function has a body. We already have the necessary information. Use it. Also prevents the `has_body` index key from being set to `true` in certain cases of parse errors/live coding.
1 parent e47ed7d commit 1983715

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

PHPCSUtils/Utils/FunctionDeclarations.php

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,10 @@ public static function getName(File $phpcsFile, $stackPtr)
7676
* Main differences with the PHPCS version:
7777
* - Bugs fixed:
7878
* - Handling of PHPCS annotations.
79+
* - `has_body` index could be set to `true` for functions without body in the case of
80+
* parse errors or live coding.
7981
* - Defensive coding against incorrect calls to this method.
82+
* - More efficient checking whether a function has a body.
8083
*
8184
* @see \PHP_CodeSniffer\Files\File::getMethodProperties() Original source.
8285
* @see \PHPCSUtils\BackCompat\BCFile::getMethodProperties() Cross-version compatible version of the original.
@@ -150,7 +153,7 @@ public static function getProperties(File $phpcsFile, $stackPtr)
150153
$returnType = '';
151154
$returnTypeToken = false;
152155
$nullableReturnType = false;
153-
$hasBody = true;
156+
$hasBody = false;
154157

155158
if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) {
156159
$scopeOpener = null;
@@ -159,10 +162,14 @@ public static function getProperties(File $phpcsFile, $stackPtr)
159162
}
160163

161164
for ($i = $tokens[$stackPtr]['parenthesis_closer']; $i < $phpcsFile->numTokens; $i++) {
162-
if (($scopeOpener === null && $tokens[$i]['code'] === \T_SEMICOLON)
163-
|| ($scopeOpener !== null && $i === $scopeOpener)
164-
) {
165+
if ($i === $scopeOpener) {
165166
// End of function definition.
167+
$hasBody = true;
168+
break;
169+
}
170+
171+
if ($scopeOpener === null && $tokens[$i]['code'] === \T_SEMICOLON) {
172+
// End of abstract/interface function definition.
166173
break;
167174
}
168175

@@ -181,12 +188,6 @@ public static function getProperties(File $phpcsFile, $stackPtr)
181188
$returnType .= $tokens[$i]['content'];
182189
}
183190
}
184-
185-
$end = $phpcsFile->findNext(
186-
[\T_OPEN_CURLY_BRACKET, \T_SEMICOLON],
187-
$tokens[$stackPtr]['parenthesis_closer']
188-
);
189-
$hasBody = $tokens[$end]['code'] === \T_OPEN_CURLY_BRACKET;
190191
}
191192

192193
if ($returnType !== '' && $nullableReturnType === true) {

0 commit comments

Comments
 (0)