Dead code detection in PHP [closed]
I have a project with very messy code - lots of duplication and dead code here and there.
Some time ago there was zero code coverage by unit-tests but now we're trying to write all new code in T.D.D. manner and lowering technical debt by covering "old" code by unit-tests as well(test-last technique).
Business logic's complexity is quite high and sometimes no one can answer whether some methods are used or not.
How this dead code methods can be found? Extensive logging? Higher test coverage?(It is not very easy because customers want new features to come out)
xdebug's code coverage tools allow you to test which lines of code are actually being executed, without needing to put trace statements in all of the functions/methods.
Example:
<?php
xdebug_start_code_coverage();
function a($a) {
echo $a * 2.5;
}
function b($count) {
for ($i = 0; $i < $count; $i++) {
a($i + 0.17);
}
}
b(6);
b(10);
var_dump(xdebug_get_code_coverage()); // array '/path/file.php' => array line_number => int 1 or 0.
?>
It's a little late now, but PHPDCD claims to do this statically, which should give you a much more informative result than having to profile actual code execution with xprof / xdebug.
I don't know of a way to detect code that is completely unused, that may be beyond the abilities of all the tools out there. But in terms of the tools out there, hit https://phpqa.io/ for a good rundown of them.
So far, one of my favorites in phploc which tears apart your code from an Object Oriented perspective and gives you details on how many classes vs how many functions vs how many tests vs average loc per function vs Cyclomatic Complexity.
My next favorite is phpcpd which is the "PHP Copy-Paste Detector". It tokenizes your entire codebase, looks for common signatures, and gives you a list of files with line numbers.
There are lots of other tools on that page, choose the ones that are useful to you.
We're actively using these tools in web2project and in the two years since we forked from dotProject, we've dropped about 35% of the codebase from refactoring, eliminating duplication (originally 12%, now about 2.5%), and generally structuring things better. And that's counting our 15k+ lines of Unit Tests. :)