From af62b4f86108d861ab04a9d895879a87438a26a3 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 3 Oct 2024 20:53:04 +0200 Subject: [PATCH] AbstractClassRestrictionsSniff: fix insufficient defensive coding 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. --- 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'] ) {