From 2a3f81e62278f488a21b70603df4cfb845af70ad Mon Sep 17 00:00:00 2001 From: Farhad Safarov Date: Fri, 10 Nov 2023 10:14:46 +0300 Subject: [PATCH] Handle UnusedClass false positive (#325) --- src/Handler/ContainerHandler.php | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Handler/ContainerHandler.php b/src/Handler/ContainerHandler.php index a4ce5a8..cdc19d0 100644 --- a/src/Handler/ContainerHandler.php +++ b/src/Handler/ContainerHandler.php @@ -9,8 +9,10 @@ use Psalm\CodeLocation; use Psalm\IssueBuffer; use Psalm\Plugin\EventHandler\AfterClassLikeVisitInterface; +use Psalm\Plugin\EventHandler\AfterCodebasePopulatedInterface; use Psalm\Plugin\EventHandler\AfterMethodCallAnalysisInterface; use Psalm\Plugin\EventHandler\Event\AfterClassLikeVisitEvent; +use Psalm\Plugin\EventHandler\Event\AfterCodebasePopulatedEvent; use Psalm\Plugin\EventHandler\Event\AfterMethodCallAnalysisEvent; use Psalm\SymfonyPsalmPlugin\Issue\NamingConventionViolation; use Psalm\SymfonyPsalmPlugin\Issue\PrivateService; @@ -20,7 +22,7 @@ use Psalm\Type\Union; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; -class ContainerHandler implements AfterMethodCallAnalysisInterface, AfterClassLikeVisitInterface +class ContainerHandler implements AfterMethodCallAnalysisInterface, AfterClassLikeVisitInterface, AfterCodebasePopulatedInterface { private const GET_CLASSLIKES = [ 'Psr\Container\ContainerInterface', @@ -165,6 +167,23 @@ public static function afterClassLikeVisit(AfterClassLikeVisitEvent $event) } } + public static function afterCodebasePopulated(AfterCodebasePopulatedEvent $event): void + { + if (null === self::$containerMeta) { + return; + } + + $containerClassNames = array_map(function (string $className): string { + return strtolower($className); + }, self::$containerMeta->getClassNames()); + + foreach ($event->getCodebase()->classlike_storage_provider->getAll() as $name => $storage) { + if (in_array($name, $containerClassNames, true)) { + $storage->suppressed_issues[] = 'UnusedClass'; + } + } + } + public static function isContainerMethod(string $declaringMethodId, string $methodName): bool { return in_array(