martin3398 / dynamic-dead-code-detector
PHP Dynamic Dead Code Detector
1.1.0
2024-04-17 20:01 UTC
Requires
- php: ^8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.53
- mikey179/vfsstream: ^1.6
- monolog/monolog: ^3.6
- phpunit/phpunit: ^10.0
- vimeo/psalm: ^5.23
Suggests
- monolog/monolog: Allow to log errors
README
This library can be used to dynamically (during runtime) detect dead classes in PHP applications.
Installation
You can install the package via composer:
composer require martin3398/php-dynamic-dead-code-detector
Usage
How to Activate during Runtime
You can use the ShutdownFunctionService
to register a shutdown function that will be called when the script ends. This function will then analyze the classes that were loaded during the script execution.
use DynamicDeadCodeDetector\Service\ShutdownFunctionService; use DynamicDeadCodeDetector\OutputHandler\FileOutputHandler; $usedClassesFile = 'used_classes.json'; $fileOutputHandler = new FileOutputHandler($usedClassesFile); $shutdownFunctionService = new ShutdownFunctionService($fileOutputHandler); $shutdownFunctionService->register();
How to find Dead Classes
Once we have the list of used classes, we can use the DeadCodeDetector
to find the dead classes.
use DynamicDeadCodeDetector\Service\DeadClassesLocatorService; $usedClassesFile = 'used_classes.json'; $deadClassesLocator = new DeadClassesLocatorService('./src', $usedClassesFile); $deadClasses = $deadClassesLocator->getDeadClasses(); foreach ($deadClasses as $deadClass) { echo $deadClass . PHP_EOL; } echo count($deadClasses) . ' dead classes found' . PHP_EOL;