Skip to content

Commit

Permalink
ContextHelper::has_object_operator_before(): simplify/use PHPCSUtils/…
Browse files Browse the repository at this point in the history
…support PHP 8.0 nullsafe object operator

* A non-inline HTML token will always have another non-empty token before it, if nothing else, the PHP open tag, so checking if `$before` is `false` is redundant.
* Implement use of the `Collections::objectOperators()` token group, which includes the PHP 8.0+ nullsafe object operator.

Includes test via the `WordPress.WP.DiscouragedFunctions` sniff.
  • Loading branch information
jrfnl committed Apr 18, 2023
1 parent 34f1ada commit 6e7e5cf
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 11 deletions.
14 changes: 3 additions & 11 deletions WordPress/Helpers/ContextHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use PHPCSUtils\Tokens\Collections;

/**
* Helper utilities for checking the context in which a token is used.
Expand Down Expand Up @@ -42,18 +43,9 @@ final class ContextHelper {
* @return bool
*/
public static function has_object_operator_before( File $phpcsFile, $stackPtr ) {
$before = $phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true, null, true );
if ( false === $before ) {
return false;
}

$tokens = $phpcsFile->getTokens();
if ( \T_OBJECT_OPERATOR !== $tokens[ $before ]['code']
&& \T_DOUBLE_COLON !== $tokens[ $before ]['code']
) {
return false;
}
$before = $phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true );

return true;
return isset( Collections::objectOperators()[ $tokens[ $before ]['code'] ] );
}
}
1 change: 1 addition & 0 deletions WordPress/Tests/WP/DiscouragedFunctionsUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ wp_reset_query(); // Warning, use wp_reset_postdata instead.
// Ensure the sniff doesn't act on methods calls.
$obj->query_posts(); // OK, not the global function.
MyClass::wp_reset_query(); // OK, not the global function.
$obj?->query_posts(); // OK, not the global function.

0 comments on commit 6e7e5cf

Please sign in to comment.