dead code detector
0.7.0
¡Extensión PHPSTAN para encontrar el código PHP no utilizado en su proyecto con facilidad!
composer require --dev shipmonk/dead-code-detectorUse el instalador de extensión oficial o simplemente cargue las reglas:
# phpstan.neon.dist
includes :
- vendor/shipmonk/dead-code-detector/rules.neon phpstan/phpstan-symfony con containerXmlPath#[AsEventListener]#[AsController]#[AsCommand]#[Required] atributo#[Route] atributosEventSubscriberInterface::getSubscribedEventsonKernelResponse , onKernelRequest , etc. #[AsEntityListener]DoctrineORMEvents::* eventosDoctrineCommonEventSubscriber Métodos#[PreFlush] , #[PostLoad] , ... testXxx@test , @before , @afterClass , etc.#[Test] , #[Before] , #[AfterClass] etc. handleXxx , renderXxx , actionXxx , injectXxx , createComponentXxxSmartObject Magic llama a @property AnnotationsTodas esas bibliotecas se encuentran automáticamente cuando se encuentran dentro de sus dependencias de compositor. Si desea forzar/deshabilitar algunos de ellos, puede:
# phpstan.neon.dist
parameters :
shipmonkDeadCode :
usageProviders :
phpunit :
enabled : true ReflectionClass se detecta como se usa$reflection->getConstructor() , $reflection->getConstant('NAME') , $reflection->getMethods() , ... vendor no se informa como muertoPsrLogLoggerInterface::log se considera automáticamente utilizadoEsos proveedores están habilitados de forma predeterminada, pero puede deshabilitarlos si es necesario.
shipmonk.deadCode.memberUsageProvider e implementa ShipMonkPHPStanDeadCodeProviderMemberUsageProvider # phpstan.neon.dist
services :
-
class : AppApiOutputUsageProvider
tags :
- shipmonk.deadCode.memberUsageProvider Importante
La interfaz y la etiqueta cambiaron en 0.7. Si está utilizando phpstan 1.x, se usaron de manera diferente.
ShipMonkPHPStanDeadCodeProviderReflectionBasedMemberUsageProvider : use ReflectionMethod ;
use ShipMonk PHPStan DeadCode Provider ReflectionBasedMemberUsageProvider ;
class ApiOutputUsageProvider extends ReflectionBasedMemberUsageProvider
{
public function shouldMarkMethodAsUsed ( ReflectionMethod $ method ): bool
{
// all methods from our ApiOutput interface are called automatically (e.g. during serialization)
return $ method -> getDeclaringClass ()-> implementsInterface (ApiOutput::class);
}
}MemberUsageProvider : use ReflectionMethod ;
use ShipMonk PHPStan DeadCode Graph ClassMethodRef ;
use ShipMonk PHPStan DeadCode Graph ClassMethodUsage ;
use ShipMonk PHPStan DeadCode Provider MemberUsageProvider ;
use Symfony Component Serializer SerializerInterface ;
class DeserializationUsageProvider implements MemberUsageProvider
{
/**
* @return list<ClassMemberUsage>
*/
public function getUsages ( Node $ node , Scope $ scope ): array
{
if (! $ node instanceof MethodCall) {
return [];
}
if (
// our deserialization calls constructor
$ scope -> getType ( $ node -> var )-> getObjectClassNames () === [SerializerInterface::class] &&
$ node -> name -> toString () === ' deserialize '
) {
$ secondArgument = $ node -> getArgs ()[ 1 ]-> value ;
$ serializedClass = $ scope -> getType ( $ secondArgument )-> getConstantStrings ()[ 0 ];
// record the method it was called from (needed for proper transitive dead code elimination)
$ originRef = $ this -> getOriginMethodRef ( $ scope );
// record the hidden constructor call
$ constructorRef = new ClassMethodRef ( $ serializedClass -> getValue (), ' __construct ' , false );
return [ new ClassMethodUsage ( $ originRef , $ constructorRef )];
}
return [];
}
private function getOriginMethodRef ( Scope $ scope ): ? ClassMethodRef
{
return new ClassMethodRef (
$ scope -> getClassReflection ()-> getName (),
$ scope -> getFunction ()-> getName (),
false ,
);
}
} ------ ------------------------------------------------------------------------
Line src/App/Facade/UserFacade.php
------ ------------------------------------------------------------------------
26 Unused AppFacadeUserFacade::updateUserAddress
? shipmonk.deadMethod
Thus AppEntityUser::updateAddress is transitively also unused
Thus AppEntityAddress::setPostalCode is transitively also unused
Thus AppEntityAddress::setCountry is transitively also unused
Thus AppEntityAddress::setStreet is transitively also unused
Thus AppEntityAddress::MAX_STREET_CHARS is transitively also unused
------ ------------------------------------------------------------------------
phpstan.neon.dist : parameters :
shipmonkDeadCode :
reportTransitivelyDeadMethodAsSeparateError : true removeDeadCode : vendor/bin/phpstan analyse --error-format removeDeadCodeclass UserFacade
{
- public const TRANSITIVELY_DEAD = 1;
-
- public function deadMethod(): void
- {
- echo self::TRANSITIVELY_DEAD;
- }
}$unknown->method() ) marcando todos los métodos nombrados method como se usanew $unknown() marcará todos los constructores tal como se usanphpstan.neon.dist :$unknown::CONSTANT ) parameters :
shipmonkDeadCode :
trackMixedAccess : false-vvv y verá algunos diagnósticos: Found 2 usages over unknown type:
• setCountry method, for example in AppEntityUser::updateAddress
• setStreet method, for example in AppEntityUser::updateAddress
__get , __set , etc.) nunca se informan como muertos__construct , __clone parameters :
ignoreErrors :
- ' # ^Unused .*?::__construct$ # ' MemberUsageProvider personalizado: use ShipMonk PHPStan DeadCode Provider ReflectionBasedMemberUsageProvider ;
class IgnoreDeadInterfaceUsageProvider extends ReflectionBasedMemberUsageProvider
{
public function shouldMarkMethodAsUsed ( ReflectionMethod $ method ): bool
{
return $ method -> getDeclaringClass ()-> isInterface ();
}
}composer checkcomposer fix:cs