logo
podcast Podcast
get help Get Unstuck

Fine-tuning Rector dead code detection

Don't let a tool boss you around

Joel Clermont
Joel Clermont
2025-07-01

Rector has a set of rules to detect dead code in your application.

When introducing Rector to a project, I like to slowly increase the number of rules used for dead code detection one level at a time to keep each change manageable to test and review.

One of the higher levels introduces a rule that removes unused variables. This seems like an obviously good thing. Why would you ever want to keep unused variables in your code?

We actually like using variables when setting up data in our test cases to make it easy to understand the purpose of that piece of data.

Consider this example where I am going to test some search logic:

// inside a test case, all factory attributes stripped out for clarity
$activeCustomerNotMatchingSearchTerm = Customer::factory()->create();
$expiredCustomerMatchingSearch = Customer::factory()->create();
$activeCustomerMatchingSearch = Customer::factory()->create();
$deletedCustomerMatchingSearch = Customer::factory()->create();

// rest of test case...

In this setup, I only expect the third customer to be returned by the search. It is the only variable I will use in a test assertion.

The Rector dead code rule would delete the variable names for the other three lines, but I think this hurts readability. Now I'd have to look more closely at the factory states and attributes to figure out why that particular customer should not match.

The variable name solves that problem, and makes it very easy to scan this test and quickly understand how it works.

Thankfully, we can configure Rector to skip this rule only in our tests directory:

// rector.php
return RectorConfig::configure()
    ->withSkip([
            \Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector::class => [
                __DIR__ . '/tests', // we like unused variables in tests for clear naming
            ],
        ]);

Now we avoid keeping unused variables in our application code, but we can keep our tests readable.

When skipping a rule, I also like to add a comment explaining why. Other developers on the project will then understand the reasoning behind that decision.

Here to help,

Joel

P.S. Would you like help introducing Rector, and other code quality tools, to your project? Let's talk!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.