Improve direct_file_access check to ignore class-only files#1147
Improve direct_file_access check to ignore class-only files#1147davidperezgar wants to merge 3 commits intotrunkfrom
direct_file_access check to ignore class-only files#1147Conversation
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
| */ | ||
| private function is_ast_valid_for_direct_access( array $ast ) { | ||
| $safe_node_types = array( | ||
| Stmt\Nop::class, |
There was a problem hiding this comment.
I'm not that familiar with the AST, but probably there should be Stmt\Declare_::class as well - if I'm reading it correctly, this would also allow
declare(strict_types=1);|
Hi, is there any way we can help move this forward? |
|
We're a little busy in Plugins team. You could propose code to this branch if you want, if not, I'll check next week. |
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