Improve direct_file_access check to ignore class-only files
#1147
+695
−10
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1146
Description
This PR improves the
direct_file_accesscheck to use AST parsing withnikic/php-parserto accurately detect files that only contain structural code (classes, interfaces, traits, namespaces) and skip them from requiring direct access guards. This reduces false positives for modern, OOP-based plugins that follow PSR-style and autoloaded architectures.The implementation uses Abstract Syntax Tree (AST) parsing to detect whether a file contains only structural code without executable statements, making the check more accurate than the previous regex-based approach.
Changes
nikic/php-parserto analyze PHP files for structural code onlyPhpParser\Node\Scalar\*class imports with string class name comparisons to avoid deprecation warningsclass_exists,function_exists, etc.) are now recognized as safeis_safe_expression()into smaller, focused methods to reduce cyclomatic complexity from 28 to below thresholdCredits
This implementation is based on the AST parsing approach used in the internal plugin review scanner, originally developed by @frantorres. The logic for detecting safe structural code has been adapted and integrated into the public Plugin Check tool.
Benefits
Testing Instructions
Test class-only files:
Test interface/trait-only files:
Test procedural code:
Test asset files:
Test safe function calls:
class_exists()orfunction_exists()with return statementsRun PHPUnit tests:
Checklist