Skip to content

Commit d0e1b1f

Browse files
committed
Fix false positive about private service in service subscriber
1 parent a5aed92 commit d0e1b1f

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Rules/Symfony/ContainerInterfacePrivateServiceRule.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
use PHPStan\Rules\Rule;
99
use PHPStan\ShouldNotHappenException;
1010
use PHPStan\Symfony\ServiceMap;
11+
use PHPStan\TrinaryLogic;
1112
use PHPStan\Type\ObjectType;
13+
use PHPStan\Type\Type;
1214
use function sprintf;
1315

1416
/**
@@ -53,7 +55,7 @@ public function processNode(Node $node, Scope $scope): array
5355

5456
$isTestContainerType = (new ObjectType('Symfony\Bundle\FrameworkBundle\Test\TestContainer'))->isSuperTypeOf($argType);
5557
$isOldServiceSubscriber = (new ObjectType('Symfony\Component\DependencyInjection\ServiceSubscriberInterface'))->isSuperTypeOf($argType);
56-
$isServiceSubscriber = (new ObjectType('Symfony\Contracts\Service\ServiceSubscriberInterface'))->isSuperTypeOf($argType);
58+
$isServiceSubscriber = $this->isServiceSubscriber($argType, $scope);
5759
$isServiceLocator = (new ObjectType('Symfony\Component\DependencyInjection\ServiceLocator'))->isSuperTypeOf($argType);
5860
if ($isTestContainerType->yes() || $isOldServiceSubscriber->yes() || $isServiceSubscriber->yes() || $isServiceLocator->yes()) {
5961
return [];
@@ -83,4 +85,12 @@ public function processNode(Node $node, Scope $scope): array
8385
return [];
8486
}
8587

88+
private function isServiceSubscriber(Type $containerType, Scope $scope): TrinaryLogic
89+
{
90+
$serviceSubscriberInterfaceType = new ObjectType('Symfony\Contracts\Service\ServiceSubscriberInterface');
91+
$containedClassType = new ObjectType($scope->getClassReflection()->getName());
92+
return $serviceSubscriberInterfaceType->isSuperTypeOf($containerType)
93+
->or($serviceSubscriberInterfaceType->isSuperTypeOf($containedClassType));
94+
}
95+
8696
}

tests/Rules/Symfony/ExampleServiceSubscriber.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,25 @@
22

33
namespace PHPStan\Rules\Symfony;
44

5+
use Psr\Container\ContainerInterface;
56
use Symfony\Contracts\Service\ServiceSubscriberInterface;
67

78
final class ExampleServiceSubscriber implements ServiceSubscriberInterface
89
{
10+
/**
11+
* @var ContainerInterface
12+
*/
13+
private $locator;
14+
15+
public function __construct(ContainerInterface $locator)
16+
{
17+
$this->locator = $locator;
18+
}
919

1020
public function privateService(): void
1121
{
1222
$this->get('private');
23+
$this->locator->get('private');
1324
}
1425

1526
public function containerParameter(): void

0 commit comments

Comments
 (0)