Skip to content
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

Resolve services subscribed to with ServiceSubscriberTrait #366

Closed
Closed
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
116 changes: 116 additions & 0 deletions src/Symfony/DefaultServiceMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@

namespace PHPStan\Symfony;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\VariadicPlaceholder;
use PhpParser\Node\Scalar\MagicConst\Method;
use PHPStan\Analyser\Scope;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionNamedType;
use PHPStan\Type\TypeUtils;
use function count;

final class DefaultServiceMap implements ServiceMap
{
const AUTOWIRE_ATTRIBUTE_CLASS = 'Symfony\Component\DependencyInjection\Attribute\Autowire';

/** @var ServiceDefinition[] */
private $services;
Expand Down Expand Up @@ -36,8 +42,118 @@ public function getService(string $id): ?ServiceDefinition

public static function getServiceIdFromNode(Expr $node, Scope $scope): ?string
{
if ($node instanceof Method) {
$serviceId = self::getServiceSubscriberId($node, $scope);
if (null !== $serviceId) {
return $serviceId;
}
}

$strings = TypeUtils::getConstantStrings($scope->getType($node));
return count($strings) === 1 ? $strings[0]->getValue() : null;
}

private static function getServiceSubscriberId(Expr $node, Scope $scope): ?string
{
$classReflection = $scope->getClassReflection();
$functionName = $scope->getFunctionName();
if ($classReflection === null ||
$functionName === null ||
!$classReflection->hasTraitUse('Symfony\Contracts\Service\ServiceSubscriberTrait')
) {
return null;
}

$methodReflection = $classReflection->getNativeReflection();
$method = $methodReflection->getMethod($functionName);
$attributes = $method->getAttributes('Symfony\Contracts\Service\Attribute\SubscribedService');
if (count($attributes) !== 1) {
return null;
}

$arguments = $attributes[0]->getArgumentsExpressions();

$autowireArgs = isset($arguments['attributes']) ?
self::getAutowireArguments($arguments['attributes'], $scope) :
[];

$value = null;
$ignoreValue = false;
foreach ($autowireArgs as $key => $arg) {
if (!$arg instanceof Arg) {
continue;
}

if ($arg->name !== null) {
$argName = $arg->name->toString();
} elseif ($key === 0) {
$argName = 'value';
} elseif ($key === 1) {
$argName = 'service';
} else {
continue;
}

// `service` argument overrules others, so break loop
$argValue = TypeUtils::getConstantStrings($scope->getType($arg->value));
$argValue = count($argValue) === 1 ? $argValue[0]->getValue() : null;

if (!is_string($argValue)) {
continue;
}

if ($argName === 'service') {
return $argValue;
}

if ($argName === 'value') {
$value = str_starts_with($argValue, '@') &&
!str_starts_with($argValue, '@@') &&
!str_starts_with($argValue, '@=') ?
substr($argValue, 1) :
$argValue;
} else {
// Can't `break` because `service` has higher priority than others
$ignoreValue = true;
}
}

// If value is provided, and no other arguments with higher priority the value is the service id
if (!$ignoreValue && $value !== null) {
return $value;
}

$returnType = $method->getReturnType();
return $returnType instanceof ReflectionNamedType ? $returnType->getName() : null;
}

/** @return array<Arg|VariadicPlaceholder> */
private static function getAutowireArguments(Expr $expression, Scope $scope): array
{
if ($expression instanceof Expr\New_) {
return $expression->class instanceof Name &&
$scope->resolveName($expression->class) === self::AUTOWIRE_ATTRIBUTE_CLASS ?
$expression->args :
[];
}

if ($expression instanceof Expr\Array_) {
foreach ($expression->items as $item) {
if ($item === null) {
continue;
}

$arg = $item->value;
if ($arg instanceof Expr\New_) {
return $arg->class instanceof Name &&
$scope->resolveName($arg->class) === self::AUTOWIRE_ATTRIBUTE_CLASS ?
$arg->args :
[];
}
}
}

return [];
}

}
35 changes: 35 additions & 0 deletions tests/Rules/Symfony/ContainerInterfaceUnknownServiceRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,41 @@ public function testGetPrivateServiceInLegacyServiceSubscriber(): void
);
}

public function testGetPrivateServiceInServiceSubscriberWithTrait(): void
{
if (!interface_exists('Symfony\Contracts\Service\ServiceSubscriberInterface')) {
self::markTestSkipped('The test needs Symfony\Contracts\Service\ServiceSubscriberInterface class.');
}

if (!trait_exists('Symfony\Contracts\Service\ServiceSubscriberTrait')) {
self::markTestSkipped('The test needs Symfony\Contracts\Service\ServiceSubscriberTrait class.');
}

$this->analyse(
[
__DIR__ . '/ExampleServiceTraitSubscriber.php',
],
[
[
'Service "unknown" is not registered in the container.',
44,
],
[
'Service "unknown" is not registered in the container.',
50,
],
[
'Service "unknown" is not registered in the container.',
56,
],
[
'Service "Baz" is not registered in the container.',
68,
],
]
);
}

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

namespace Rules\Symfony;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\Service\Attribute\SubscribedService;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Service\ServiceSubscriberTrait;

final class ExampleServiceTraitSubscriber implements ServiceSubscriberInterface
{
use ServiceSubscriberTrait;

/** @var ContainerInterface */
private $locator;

public function __construct(ContainerInterface $locator)
{
$this->locator = $locator;
}

#[SubscribedService(attributes: new Autowire('private'))]
private function getIndexed(): Foo
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService(attributes: new Autowire(value: 'private'))]
private function getNamedValue(): Foo
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService(attributes: new Autowire(service: 'private'))]
private function getNamedService(): Foo
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService(attributes: new Autowire('unknown'))]
private function getUnknownIndexed(): Foo
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService(attributes: new Autowire(value: 'unknown'))]
private function getUnknownNamedValue(): Foo
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService(attributes: new Autowire(service: 'unknown'))]
private function getUnknownNamedService(): Foo
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService]
public function getBar(): \Bar
{
return $this->locator->get(__METHOD__);
}

#[SubscribedService]
public function getBaz(): \Baz
{
return $this->locator->get(__METHOD__);
}
}
1 change: 1 addition & 0 deletions tests/Rules/Symfony/container.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
<argument key="private" type="service" id="private"/>
</argument>
</service>
<service id="Bar" class="Bar"></service>
</services>
</container>