Unused code is probably one of the most basic code smells that you can have. It is code that you have needed at some point, but somewhere along the way, it became unused. In most cases, it is very easy to fix.
PHP Analyzer detects several types of unused code, and it is very deliberate about marking something as unused. If in doubt, it will not mark something to avoid generating false-positives for such a low risk issue.
This pass checks that the methods which you use are called at least once from somewhere. Also, if you use a dynamic calls, let’s say $this->$x();, PHP Analyzer will mark all the possible methods this call could reach as used.
PHP Analyzer also checks whether your parameters are used. This may sound simple, but this is actually one of the longest analyses of PHP Analyzer as we need to analyze not only your immediate code, but actually your entire type hierarchy. Let’s take a look at an example:
abstract class Command
{
public function run()
{
// ...
$rs = $this->execute($input, $output);
// ...
}
protected function execute($input, $output)
{
// Overridden in child classes.
}
}
class MyFirstCommand extends Command
{
protected function execute($input, $output)
{
$output->writeln('Doing something.');
}
}
class MySecondCommand extends Command
{
protected function execute($input, $output)
{
$x = $input->getArgument('x');
// doing something with $x.
}
}
In the above example, if we were just looking at the individual methods, we would need to label several parameters as unused:
However, in fact the execute() methods are all part of the same interface, and each parameter is used in at least one place. So, PHP Analyzer will correctly label none of these parameters as unused.
This analysis is a bit simpler again, as we just need to consider the body of a function or method:
function filteringSomething(array $groups, callable $predicate) {
$filtersGroups = array();
foreach ($groups as $group) {
if ($predicate($group) === true) {
$filterGroups[] = $group;
}
}
return $filterGroups;
}
As you can see, the first assignment to $filtersGroups (note the additional s), is not used anywhere else. For such small typos, PHP Analyzer will even suggest to correct the variable name instead of marking it as unused.
Just like for the other unused code checks, if a variable might be accessed in some dynamic fashion like ${$x} for example, PHP Analyzer will mark all the variables which might be accessed by it as used.