Skip to content

Improve direct_file_access check to ignore class-only files #1146

@davidperezgar

Description

@davidperezgar

The direct_file_access check currently flags PHP files that do not include an explicit protection against direct access (e.g. defined( 'ABSPATH' ) || exit;).

However, this behaviour can produce false positives for files that:

  • Contain only class definitions
  • Do not execute any logic on load
  • Are intended to be included or autoloaded, not accessed directly

Current Behaviour

Files that only declare classes (no side effects, no executable code) are still reported by the direct_file_access check if they lack an ABSPATH guard.

Example:

<?php

class My_Plugin_Service {
    public function do_something() {
        // ...
    }
}

This file is flagged, even though direct access would not produce output or cause unintended behavior.

Expected Behavior

The direct_file_access check should skip or ignore PHP files that only contain class declarations, provided that:

  • No code is executed at the top level
  • No functions are called outside class/method scope
  • No side effects (echo, include, require, hooks, etc.) are present

Proposed Improvement

Enhance the check logic to detect whether a file contains only structural code, such as:

  • class, interface, or trait declarations
  • Namespaces and use statements
  • PHPDoc blocks

If so, the file should not require a direct access guard and should not be reported.

Benefits

  • Reduces false positives in modern, OOP-based plugins
  • Aligns better with PSR-style and autoloaded architectures
  • Improves developer experience and signal-to-noise ratio of Plugin Check

Additional Notes

This could potentially be implemented using AST parsing (e.g. via nikic/php-parser) or by enhancing the existing token-based analysis to detect top-level executable statements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    [Team] PluginsIssues owned by Plugins Team

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions