martin3398/dynamic-dead-code-detector

PHP Dynamic Dead Code Detector

1.1.0 2024-04-17 20:01 UTC

This package is auto-updated.

Last update: 2024-05-17 20:09:29 UTC


README

Build

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;