Skip to content

[DeadCode] Add RemovePsr4AutoloadedIncludeRector#8149

Open
TomasVotruba wants to merge 2 commits into
mainfrom
tv-remove-dead-include-require
Open

[DeadCode] Add RemovePsr4AutoloadedIncludeRector#8149
TomasVotruba wants to merge 2 commits into
mainfrom
tv-remove-dead-include-require

Conversation

@TomasVotruba

@TomasVotruba TomasVotruba commented Jul 6, 2026

Copy link
Copy Markdown
Member

Inspired at https://www.reddit.com/r/PHP/comments/1unb59g/i_built_a_static_analysis_tool_that_finds_require/

I'm surprised we don't have this rule yet, so obvious :)

Caveats

  • verify dir autoload?

Adds RemovePsr4AutoloadedIncludeRector (DeadCode). Removes a standalone include/require when the target file is already covered by a PSR-4 autoload mapping in composer.json — the composer autoloader loads the class anyway, so the manual require is dead.

Before / after

-require __DIR__ . '/src/SomeClass.php';
-
 $someClass = new App\SomeClass();

with composer.json:

{
    "autoload": {
        "psr-4": { "App\\": "src" }
    }
}

How it decides

  1. Matches only a bare statement require X; (skips $x = require ...;).
  2. Resolves the target path (__DIR__ . '/rel.php', absolute, or relative literal) against the current file dir.
  3. Parses the target; bails unless it declares exactly one class — otherwise removing the require would drop the other definitions.
  4. Reads autoload + autoload-dev PSR-4 from composer.json (auto-found at project root via getcwd(), or set COMPOSER_JSON_PATH).
  5. Removes only if the declared FQCN maps back to that exact file through a PSR-4 prefix.

Skips (covered by fixtures)

  • file not under any PSR-4 path
  • file declaring 2+ classes
  • $x = require ...; (non-standalone include)

Configurable rule (does filesystem I/O), so it is not added to the dead-code level set — opt-in via config.

@samsonasik

samsonasik commented Jul 6, 2026

Copy link
Copy Markdown
Member

I think this should skip if the class has side effect directly in target source:

namespace App;

class Cli 
{
    public static function init() {
         // init cli ...
    }
}

// here init on purpose
Cli::init();

for example

https://github.com/codeigniter4/CodeIgniter4/blob/d9ec94b7ec4bbded8d66a8dc07ed8ceb7f402f69/system/CLI/CLI.php#L1191-L1192

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants