From 0988a5aed1fb34d148d28510cd5c65a2c39ecd79 Mon Sep 17 00:00:00 2001 From: Juliette <663378+jrfnl@users.noreply.github.com> Date: Fri, 4 Oct 2024 21:05:04 +0200 Subject: [PATCH] AbstractClassRestrictionsSniff: fix insufficient defensive coding (#2500) This commit fixes the test failure seen in PR 2499. The test failure was surfaced due to a new exception in PHPCS (see: PHPCSStandards/PHP_CodeSniffer 524), which will be included in PHPCS 3.11.0. The test failure highlighted that the above mentioned PHPCS PR needs a follow-up with some extra defensive coding, however, that defensive coding is needed in a part in PHPCS which does the error handling for PHP notices being encountered, i.e. the throwing of `Internal.Exception` errors. This implied there was also an underlying issue in WPCS causing the `Internal.Exception`, which apparently was only triggered when the fixer was being run. > Note: the fact that `Internal.Exception`s during a PHPCBF run are being suppressed is a known issue, but fixing that is not that easy, so that definitely won't happen before PHPCS 4.0 (and may not even make it into 4.0). See: squizlabs/PHP_CodeSniffer 2871 Either way, I've looked into the `Internal.Exception` now. The error was as follows: ``` An error occurred during processing; checking has been aborted. The error message was: PHPCSUtils\Utils\GetTokensAsString::getString(): Argument #2 ($start) must be a stack pointer which exists in the $phpcsFile object, 8 given. The error originated in the AbstractClassRestrictionsSniff.php sniff on line 131. ``` The additional defensive coding added in this commit, fixes the issue. Co-authored-by: jrfnl --- WordPress/AbstractClassRestrictionsSniff.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/WordPress/AbstractClassRestrictionsSniff.php b/WordPress/AbstractClassRestrictionsSniff.php index e41cd3631..89dce6b85 100644 --- a/WordPress/AbstractClassRestrictionsSniff.php +++ b/WordPress/AbstractClassRestrictionsSniff.php @@ -128,8 +128,10 @@ public function is_targetted_token( $stackPtr ) { $nameEnd = ( $this->phpcsFile->findNext( array( \T_CLOSE_CURLY_BRACKET, \T_WHITESPACE ), ( $stackPtr + 2 ) ) - 1 ); } - $classname = GetTokensAsString::noEmpties( $this->phpcsFile, ( $stackPtr + 2 ), $nameEnd ); - $classname = $this->get_namespaced_classname( $classname, ( $stackPtr - 1 ) ); + if ( isset( $this->tokens[ $stackPtr + 2 ] ) && false !== $nameEnd ) { + $classname = GetTokensAsString::noEmpties( $this->phpcsFile, ( $stackPtr + 2 ), $nameEnd ); + $classname = $this->get_namespaced_classname( $classname, ( $stackPtr - 1 ) ); + } } if ( \T_DOUBLE_COLON === $token['code'] ) {