Skip to content

Support Symfony #[AutowireLocator] attribute #420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: 1.4.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 34 additions & 9 deletions src/Rules/Symfony/ContainerInterfacePrivateServiceRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Symfony\AutowireLocatorServiceMapFactory;
use PHPStan\Symfony\DefaultServiceMap;
use PHPStan\Symfony\ServiceMap;
use PHPStan\TrinaryLogic;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use function is_null;
use function sprintf;

/**
Expand Down Expand Up @@ -66,15 +69,25 @@ public function processNode(Node $node, Scope $scope): array
}

$serviceId = $this->serviceMap::getServiceIdFromNode($node->getArgs()[0]->value, $scope);
if ($serviceId !== null) {
$service = $this->serviceMap->getService($serviceId);
if ($service !== null && !$service->isPublic()) {
return [
RuleErrorBuilder::message(sprintf('Service "%s" is private.', $serviceId))
->identifier('symfonyContainer.privateService')
->build(),
];
}
if ($serviceId === null) {
return [];
}

$isContainerInterfaceType = $isContainerType->yes() || $isPsrContainerType->yes();
if (
$isContainerInterfaceType &&
$this->isAutowireLocatorService($node, $scope, $serviceId)
) {
return [];
}

$service = $this->serviceMap->getService($serviceId);
if ($service !== null && !$service->isPublic()) {
return [
RuleErrorBuilder::message(sprintf('Service "%s" is private.', $serviceId))
->identifier('symfonyContainer.privateService')
->build(),
];
}

return [];
Expand All @@ -92,4 +105,16 @@ private function isServiceSubscriber(Type $containerType, Scope $scope): Trinary
return $isContainerServiceSubscriber->or($serviceSubscriberInterfaceType->isSuperTypeOf($containedClassType));
}

private function isAutowireLocatorService(Node $node, Scope $scope, string $serviceId): bool
{
$autowireLocatorServiceMapFactory = new AutowireLocatorServiceMapFactory($node, $scope);
$autowireLocatorServiceMap = $autowireLocatorServiceMapFactory->create();

if (!$autowireLocatorServiceMap instanceof DefaultServiceMap) {
return false;
}

return !is_null($autowireLocatorServiceMap->getService($serviceId));
}

}
54 changes: 47 additions & 7 deletions src/Rules/Symfony/ContainerInterfaceUnknownServiceRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@
use PhpParser\Node\Expr\MethodCall;
use PhpParser\PrettyPrinter\Standard;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Symfony\AutowireLocatorServiceMapFactory;
use PHPStan\Symfony\DefaultServiceMap;
use PHPStan\Symfony\ServiceMap;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Symfony\Helper;
Expand Down Expand Up @@ -66,19 +69,56 @@ public function processNode(Node $node, Scope $scope): array
}

$serviceId = $this->serviceMap::getServiceIdFromNode($node->getArgs()[0]->value, $scope);
if ($serviceId !== null) {
$service = $this->serviceMap->getService($serviceId);
$serviceIdType = $scope->getType($node->getArgs()[0]->value);
if ($service === null && !$scope->getType(Helper::createMarkerNode($node->var, $serviceIdType, $this->printer))->equals($serviceIdType)) {
if ($serviceId === null) {
return [];
}

$isContainerInterfaceType = $isContainerType->yes() || $isPsrContainerType->yes();
if ($isContainerInterfaceType) {
$autowireLoaderResult = $this->getAutowireLocatorResult($node, $scope, $serviceId);

if ($autowireLoaderResult !== null) {
return $autowireLoaderResult;
}
}

$service = $this->serviceMap->getService($serviceId);
$serviceIdType = $scope->getType($node->getArgs()[0]->value);
if ($service === null && !$scope->getType(Helper::createMarkerNode($node->var, $serviceIdType, $this->printer))->equals($serviceIdType)) {
return [
RuleErrorBuilder::message(sprintf('Service "%s" is not registered in the container.', $serviceId))
->identifier('symfonyContainer.serviceNotFound')
->build(),
];
}

return [];
}

/**
* @return list<IdentifierRuleError>|null
*/
private function getAutowireLocatorResult(Node $node, Scope $scope, string $serviceId): ?array
{
$autowireLocatorServiceMapFactory = new AutowireLocatorServiceMapFactory($node, $scope);
$autowireLocatorServiceMap = $autowireLocatorServiceMapFactory->create();

// Our container has a valid AutowireLocator attribute, else we would get a FakeServiceMap.
if ($autowireLocatorServiceMap instanceof DefaultServiceMap) {
$autowireLocatorService = $autowireLocatorServiceMap->getService($serviceId);

if ($autowireLocatorService === null) {
return [
RuleErrorBuilder::message(sprintf('Service "%s" is not registered in the container.', $serviceId))
->identifier('symfonyContainer.serviceNotFound')
RuleErrorBuilder::message(sprintf('Service "%s" is not registered in the AutowireLocator.', $serviceId))
->identifier('symfonyContainer.undefinedService')
->build(),
];
}

return [];
}

return [];
return null;
}

}
110 changes: 110 additions & 0 deletions src/Symfony/AutowireLocatorServiceMapFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php declare(strict_types = 1);

namespace PHPStan\Symfony;

use InvalidArgumentException;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
use Symfony\Component\DependencyInjection\TypedReference;
use function class_exists;
use function count;
use function sprintf;

final class AutowireLocatorServiceMapFactory implements ServiceMapFactory
{

/** @var Node */
private $node;

/** @var Scope */
private $scope;

public function __construct(
Node $node,
Scope $scope
)
{
$this->node = $node;
$this->scope = $scope;
}

public function create(): ServiceMap
{
if (!class_exists('Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator')) {
return new FakeServiceMap();
}

if (!$this->node instanceof MethodCall) {
return new FakeServiceMap();
}

$nodeParentProperty = $this->node->var;

if (!$nodeParentProperty instanceof Node\Expr\PropertyFetch) {
return new FakeServiceMap();
}

$nodeParentPropertyName = $nodeParentProperty->name;

if (!$nodeParentPropertyName instanceof Node\Identifier) {
return new FakeServiceMap();
}

$containerInterfacePropertyName = $nodeParentPropertyName->name;
$scopeClassReflection = $this->scope->getClassReflection();

if (!$scopeClassReflection instanceof ClassReflection) {
return new FakeServiceMap();
}

$containerInterfacePropertyReflection = $scopeClassReflection
->getNativeProperty($containerInterfacePropertyName);
$classPropertyReflection = $containerInterfacePropertyReflection->getNativeReflection();
$autowireLocatorAttributesReflection = $classPropertyReflection->getAttributes(AutowireLocator::class);

if (count($autowireLocatorAttributesReflection) === 0) {
return new FakeServiceMap();
}

if (count($autowireLocatorAttributesReflection) > 1) {
throw new InvalidArgumentException(sprintf(
'Only one AutowireLocator attribute is allowed on "%s::%s".',
$scopeClassReflection->getName(),
$containerInterfacePropertyName
));
}

$autowireLocatorAttributeReflection = $autowireLocatorAttributesReflection[0];
/** @var AutowireLocator $autowireLocator */
$autowireLocator = $autowireLocatorAttributeReflection->newInstance();
$serviceLocatorArgument = $autowireLocator->value;

if (!$serviceLocatorArgument instanceof ServiceLocatorArgument) {
return new FakeServiceMap();
}

/** @var Service[] $services */
$services = [];

/** @var TypedReference $service */
foreach ($serviceLocatorArgument->getValues() as $id => $service) {
$class = $service->getType();
$alias = $service->getName();

$services[$id] = new Service(
$id,
$class,
true,
false,
$alias
);
}

return new DefaultServiceMap($services);
}

}
34 changes: 34 additions & 0 deletions tests/Rules/Symfony/ContainerInterfacePrivateServiceRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PHPStan\Testing\RuleTestCase;
use function class_exists;
use function interface_exists;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<ContainerInterfacePrivateServiceRule>
Expand Down Expand Up @@ -78,4 +79,37 @@ public function testGetPrivateServiceInServiceSubscriber(): void
);
}

public function testGetPrivateServiceWithoutAutowireLocatorAttribute(): void
{
if (PHP_VERSION_ID < 80000) {
self::markTestSkipped('The test uses PHP Attributes which are available since PHP 8.0.');
}

$this->analyse(
[
__DIR__ . '/ExampleAutowireLocatorEmptyService.php',
],
[
[
'Service "private" is private.',
22,
],
]
);
}

public function testGetPrivateServiceViaAutowireLocatorAttribute(): void
{
if (PHP_VERSION_ID < 80000) {
self::markTestSkipped('The test uses PHP Attributes which are available since PHP 8.0.');
}

$this->analyse(
[
__DIR__ . '/ExampleAutowireLocatorService.php',
],
[]
);
}

}
38 changes: 38 additions & 0 deletions tests/Rules/Symfony/ContainerInterfaceUnknownServiceRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PHPStan\Testing\RuleTestCase;
use function class_exists;
use function interface_exists;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<ContainerInterfaceUnknownServiceRule>
Expand Down Expand Up @@ -72,6 +73,43 @@ public function testGetPrivateServiceInLegacyServiceSubscriber(): void
);
}

public function testGetPrivateServiceWithoutAutowireLocatorAttribute(): void
{
if (PHP_VERSION_ID < 80000) {
self::markTestSkipped('The test uses PHP Attributes which are available since PHP 8.0.');
}

$this->analyse(
[
__DIR__ . '/ExampleAutowireLocatorEmptyService.php',
],
[
[
'Service "Foo" is not registered in the AutowireLocator.',
21,
],
[
'Service "private" is not registered in the AutowireLocator.',
22,
],
]
);
}

public function testGetPrivateServiceViaAutowireLocatorAttribute(): void
{
if (PHP_VERSION_ID < 80000) {
self::markTestSkipped('The test uses PHP Attributes which are available since PHP 8.0.');
}

$this->analyse(
[
__DIR__ . '/ExampleAutowireLocatorService.php',
],
[]
);
}

public static function getAdditionalConfigFiles(): array
{
return [
Expand Down
25 changes: 25 additions & 0 deletions tests/Rules/Symfony/ExampleAutowireLocatorEmptyService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;

final class ExampleAutowireLocatorEmptyService
{

public function __construct(
#[AutowireLocator([])]
private ContainerInterface $locator
)
{
$this->locator = $locator;
}

public function privateServiceInLocator(): void
{
$this->locator->get('Foo');
$this->locator->get('private');
}

}
Loading
Loading