Skip to content
Merged
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ vendor/bin/psalm-plugin enable psalm/plugin-symfony
### Features

- Detect `ContainerInterface::get()` result type. Works better if you [configure](#configuration) compiled container XML file.
- Support [Service Subscribers](https://github.com/psalm/psalm-plugin-symfony/issues/20).
- Detect return type of console arguments (`InputInterface::getArgument()`) and options (`InputInterface::getOption()`). Enforces
to use InputArgument and InputOption constants as a part of best practise.
- Detects correct Doctrine repository class if entities are configured with annotations.
Expand Down
48 changes: 42 additions & 6 deletions src/Handler/ContainerHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Return_;
use Psalm\Codebase;
use Psalm\CodeLocation;
use Psalm\Context;
Expand All @@ -19,6 +22,7 @@
use Psalm\SymfonyPsalmPlugin\Issue\PrivateService;
use Psalm\SymfonyPsalmPlugin\Issue\ServiceNotFound;
use Psalm\SymfonyPsalmPlugin\Symfony\ContainerMeta;
use Psalm\SymfonyPsalmPlugin\Symfony\Service;
use Psalm\Type\Atomic\TNamedObject;
use Psalm\Type\Union;

Expand Down Expand Up @@ -58,7 +62,7 @@ public static function afterMethodCallAnalysis(
if (!self::isContainerMethod($declaring_method_id, 'get')) {
if (self::isContainerMethod($declaring_method_id, 'getparameter')) {
$argument = $expr->args[0]->value;
if ($argument instanceof String_ && !self::followsNamingConvention($argument->value)) {
if ($argument instanceof String_ && !self::followsNamingConvention($argument->value) && false === strpos($argument->value, '\\')) {
IssueBuffer::accepts(
new NamingConventionViolation(new CodeLocation($statements_source, $argument)),
$statements_source->getSuppressedIssues()
Expand Down Expand Up @@ -90,7 +94,7 @@ public static function afterMethodCallAnalysis(

$service = self::$containerMeta->get($serviceId);
if ($service) {
if (!self::followsNamingConvention($serviceId) && !class_exists($service->getClassName())) {
if (!self::followsNamingConvention($serviceId) && false === strpos($serviceId, '\\')) {
IssueBuffer::accepts(
new NamingConventionViolation(new CodeLocation($statements_source, $expr->args[0]->value)),
$statements_source->getSuppressedIssues()
Expand Down Expand Up @@ -130,14 +134,46 @@ public static function afterClassLikeVisit(
Codebase $codebase,
array &$file_replacements = []
) {
$fileStorage = $codebase->file_storage_provider->get($statements_source->getFilePath());

if (\in_array($storage->name, ContainerHandler::GET_CLASSLIKES)) {
if (self::$containerMeta) {
$file_path = $statements_source->getFilePath();
$file_storage = $codebase->file_storage_provider->get($file_path);

foreach (self::$containerMeta->getClassNames() as $className) {
$codebase->queueClassLikeForScanning($className);
$file_storage->referenced_classlikes[strtolower($className)] = $className;
$fileStorage->referenced_classlikes[strtolower($className)] = $className;
}
}
}

// see https://symfony.com/doc/current/service_container/service_subscribers_locators.html
if (self::$containerMeta && $stmt instanceof Class_ && isset($storage->class_implements['symfony\contracts\service\servicesubscriberinterface'])) {
foreach ($stmt->stmts as $classStmt) {
if ($classStmt instanceof ClassMethod && 'getSubscribedServices' === $classStmt->name->name && $classStmt->stmts) {
foreach ($classStmt->stmts as $methodStmt) {
if ($methodStmt instanceof Return_ && ($return = $methodStmt->expr) && $return instanceof Expr\Array_) {
foreach ($return->items as $arrayItem) {
if ($arrayItem instanceof Expr\ArrayItem) {
$value = $arrayItem->value;
if (!$value instanceof Expr\ClassConstFetch) {
continue;
}

/** @var string $className */
$className = $value->class->getAttribute('resolvedName');

$key = $arrayItem->key;
$serviceId = $key instanceof String_ ? $key->value : $className;

$service = new Service($serviceId, $className);
$service->setIsPublic(true);
self::$containerMeta->add($service);

$codebase->queueClassLikeForScanning($className);
$fileStorage->referenced_classlikes[strtolower($className)] = $className;
}
}
}
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/ContainerMeta.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function get(string $id): ?Service
return null;
}

private function add(Service $service): void
public function add(Service $service): void
{
if (($alias = $service->getAlias()) && isset($this->services[$alias])) {
$aliasedService = $this->services[$alias];
Expand Down
64 changes: 64 additions & 0 deletions tests/acceptance/acceptance/ServiceSubscriber.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
@symfony-4 @symfony-5
Feature: Service Subscriber

Background:
Given I have the following config
"""
<?xml version="1.0"?>
<psalm errorLevel="1">
<projectFiles>
<directory name="."/>
<ignoreFiles> <directory name="../../vendor"/> </ignoreFiles>
</projectFiles>

<plugins>
<pluginClass class="Psalm\SymfonyPsalmPlugin\Plugin">
<containerXml>../../tests/acceptance/container.xml</containerXml>
</pluginClass>
</plugins>
</psalm>
"""

Scenario: Asserting psalm recognizes return type of services defined in getSubscribedServices
Given I have the following code
"""
<?php

use Doctrine\ORM\EntityManagerInterface;
use Psr\Container\ContainerInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class SomeController implements ServiceSubscriberInterface
{
private $container;

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

public function __invoke()
{
/** @psalm-trace $entityManager */
$entityManager = $this->container->get('em');

/** @psalm-trace $validator */
$validator = $this->container->get(ValidatorInterface::class);
}

public static function getSubscribedServices()
{
return [
'em' => EntityManagerInterface::class, // with key
ValidatorInterface::class, // without key
];
}
}
"""
When I run Psalm
Then I see these errors
| Type | Message |
| Trace | $entityManager: Doctrine\ORM\EntityManagerInterface |
| Trace | $validator: Symfony\Component\Validator\Validator\ValidatorInterface |
And I see no other errors