PHPackages                             phpstan/phpstan-symfony - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. phpstan/phpstan-symfony

ActivePhpstan-extension[Testing &amp; Quality](/categories/testing)

phpstan/phpstan-symfony
=======================

Symfony Framework extensions and rules for PHPStan

2.0.15(2mo ago)78768.9M—6.3%101[60 issues](https://github.com/phpstan/phpstan-symfony/issues)[13 PRs](https://github.com/phpstan/phpstan-symfony/pulls)20MITPHPPHP ^7.4 || ^8.0CI passing

Since Jun 21Pushed today8 watchersCompare

[ Source](https://github.com/phpstan/phpstan-symfony)[ Packagist](https://packagist.org/packages/phpstan/phpstan-symfony)[ RSS](/packages/phpstan-phpstan-symfony/feed)WikiDiscussions 2.0.x Synced 1mo ago

READMEChangelog (10)Dependencies (32)Versions (158)Used By (20)

PHPStan Symfony Framework extensions and rules
==============================================

[](#phpstan-symfony-framework-extensions-and-rules)

[![Build](https://github.com/phpstan/phpstan-symfony/workflows/Build/badge.svg)](https://github.com/phpstan/phpstan-symfony/actions)[![Latest Stable Version](https://camo.githubusercontent.com/32192bf23ce42f22d10760e124ec2c92d21c409a0216debb1b55b849669043bc/68747470733a2f2f706f7365722e707567782e6f72672f7068707374616e2f7068707374616e2d73796d666f6e792f762f737461626c65)](https://packagist.org/packages/phpstan/phpstan-symfony)[![License](https://camo.githubusercontent.com/7b2ff906e3b8f412e658db96829217c6773a15ade0efcfc3015ba625bbd31d45/68747470733a2f2f706f7365722e707567782e6f72672f7068707374616e2f7068707374616e2d73796d666f6e792f6c6963656e7365)](https://packagist.org/packages/phpstan/phpstan-symfony)

- [PHPStan](https://phpstan.org/)

This extension provides following features:

- Provides correct return type for `ContainerInterface::get()` and `::has()` methods.
- Provides correct return type for `Controller::get()` and `::has()` methods.
- Provides correct return type for `AbstractController::get()` and `::has()` methods.
- Provides correct return type for `ContainerInterface::getParameter()` and `::hasParameter()` methods.
- Provides correct return type for `ParameterBagInterface::get()` and `::has()` methods.
- Provides correct return type for `Controller::getParameter()` method.
- Provides correct return type for `AbstractController::getParameter()` method.
- Provides correct return type for `Request::getContent()` method based on the `$asResource` parameter.
- Provides correct return type for `HeaderBag::get()` method based on the `$first` parameter.
- Provides correct return type for `Envelope::all()` method based on the `$stampFqcn` parameter.
- Provides correct return type for `InputBag::get()` method based on the `$default` parameter.
- Provides correct return type for `InputBag::all()` method based on the `$key` parameter.
- Provides correct return type for `ResponseHeaderBag::getCookies()` method based on the format argument.
- Provides correct return types for `TreeBuilder` and `NodeDefinition` objects.
- Provides correct return type for `SerializerInterface::deserialize()` and `DenormalizerInterface::denormalize()` methods based on the `$type` argument.
- Provides correct return type for `HandleTrait::handle()` method based on the message handler map.
- Provides correct return type for `FormInterface::getErrors()` method based on the `$deep` and `$flatten` parameters.
- Provides correct return type for `KernelInterface::locateResource()` method.
- Provides correct return type for `Extension::getConfiguration()` method.
- Provides correct return type for `CacheInterface::get()` method based on the callback return type.
- Provides correct return type for `BrowserKitAssertionsTrait::getClient()` method.
- Provides configurable return type resolution for methods that internally use Messenger `HandleTrait`.
- Notifies you when you try to get an unregistered service from the container.
- Notifies you when you try to get a private service from the container.
- Notifies you when you access undefined console command arguments or options.
- Validates default values of console command arguments and options.
- Recognizes `@required` annotation and `#[Required]` attribute for autowiring properties and methods.
- Optionally correct return types for `InputInterface::getArgument()`, `::getOption()`, `::getOptions()`, `::hasArgument()`, and `::hasOption()`.
- Optionally provides correct return type for `Command::getHelper()` method.

Installation
------------

[](#installation)

To use this extension, require it in [Composer](https://getcomposer.org/):

```
composer require --dev phpstan/phpstan-symfony

```

If you also install [phpstan/extension-installer](https://github.com/phpstan/extension-installer) then you're all set!

 Manual installationIf you don't want to use `phpstan/extension-installer`, include extension.neon in your project's PHPStan config:

```
includes:
    - vendor/phpstan/phpstan-symfony/extension.neon

```

To perform framework-specific checks, include also this file:

```
includes:
    - vendor/phpstan/phpstan-symfony/rules.neon

```

Configuration
=============

[](#configuration)

You have to provide a path to `srcDevDebugProjectContainer.xml` or similar XML file describing your container.

```
parameters:
    symfony:
        containerXmlPath: var/cache/dev/srcDevDebugProjectContainer.xml
        # or with Symfony 4.2+
        containerXmlPath: var/cache/dev/srcApp_KernelDevDebugContainer.xml
        # or with Symfony 5+
        containerXmlPath: var/cache/dev/App_KernelDevDebugContainer.xml
    # If you're using PHP config files for Symfony 5.3+, you also need this for auto-loading of `Symfony\Config`:
    scanDirectories:
        - var/cache/dev/Symfony/Config
    # If you're using PHP config files (including the ones under packages/*.php) for Symfony 5.3+,
    # you need this to load the helper functions (i.e. service(), env()):
    scanFiles:
        - vendor/symfony/dependency-injection/Loader/Configurator/ContainerConfigurator.php
```

Constant hassers
----------------

[](#constant-hassers)

Sometimes, when you are dealing with optional dependencies, the `::has()` methods can cause problems. For example, the following construct would complain that the condition is always either on or off, depending on whether you have the dependency for `service` installed:

```
if ($this->has('service')) {
    // ...
}
```

In that case, you can disable the `::has()` method return type resolving like this:

```
parameters:
	symfony:
		constantHassers: false

```

Be aware that it may hide genuine errors in your application.

Analysis of Symfony Console Commands
------------------------------------

[](#analysis-of-symfony-console-commands)

You can opt in for more advanced analysis of [Symfony Console Commands](https://symfony.com/doc/current/console.html)by providing the console application from your own application. This will allow the correct argument and option types to be inferred when accessing `$input->getArgument()` or `$input->getOption()`.

```
parameters:
	symfony:
		consoleApplicationLoader: tests/console-application.php
```

Symfony 4:

```
// tests/console-application.php

use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;

require __DIR__ . '/../config/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
return new Application($kernel);
```

Symfony 5:

```
// tests/console-application.php

use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Dotenv\Dotenv;

require __DIR__ . '/../vendor/autoload.php';

(new Dotenv())->bootEnv(__DIR__ . '/../.env');

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
return new Application($kernel);
```

[Single Command Application](https://symfony.com/doc/current/components/console/single_command_tool.html):

```
// tests/console-application.php

use App\Application; // where Application extends Symfony\Component\Console\SingleCommandApplication
use Symfony\Component\Console;

require __DIR__ . '/../vendor/autoload.php';

$application = new Console\Application();
$application->add(new Application());

return $application;
```

You may then encounter an error with PhpParser:

> Compile Error: Cannot Declare interface PhpParser\\NodeVisitor, because the name is already in use

If this is the case, you should create a new environment for your application that will disable inlining. In `config/packages/phpstan_env/parameters.yaml`:

```
parameters:
    container.dumper.inline_class_loader: false
```

Call the new env in your `console-application.php`:

```
$kernel = new \App\Kernel('phpstan_env', (bool) $_SERVER['APP_DEBUG']);
```

Messenger HandleTrait Wrappers
------------------------------

[](#messenger-handletrait-wrappers)

The extension provides advanced type inference for methods that internally use Symfony Messenger's `HandleTrait`. This feature is particularly useful for query bus implementations (in CQRS pattern) that use/wrap the `HandleTrait::handle()` method.

### Configuration

[](#configuration-1)

```
parameters:
    symfony:
        messenger:
            handleTraitWrappers:
                - App\Bus\QueryBus::dispatch
                - App\Bus\QueryBus::execute
                - App\Bus\QueryBusInterface::dispatch
```

### Message Handlers

[](#message-handlers)

```
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

// Product handler that returns Product
#[AsMessageHandler]
class GetProductQueryHandler
{
    public function __invoke(GetProductQuery $query): Product
    {
        return $this->productRepository->get($query->productId);
    }
}
```

### PHP Examples

[](#php-examples)

```
use Symfony\Component\Messenger\HandleTrait;
use Symfony\Component\Messenger\MessageBusInterface;

// Basic query bus implementation
class QueryBus
{
    use HandleTrait;

    public function __construct(MessageBusInterface $messageBus)
    {
        $this->messageBus = $messageBus;
    }

    public function dispatch(object $query): mixed
    {
        return $this->handle($query); // Return type will be inferred in calling code as query result
    }

    // Multiple methods per class example
    public function execute(object $message): mixed
    {
        return $this->handle($message); // Return type will be inferred in calling code as query result
    }
}

// Interface-based configuration example
interface QueryBusInterface
{
    public function dispatch(object $query): mixed; // Return type will be inferred in calling code as query result
}

class QueryBusWithInterface implements QueryBusInterface
{
    use HandleTrait;

    public function __construct(MessageBusInterface $queryBus)
    {
        $this->messageBus = $queryBus;
    }

    public function dispatch(object $query): mixed
    {
        return $this->handle($query);
    }
}

// Examples of use with proper type inference
$query = new GetProductQuery($productId);
$queryBus = new QueryBus($messageBus);
$queryBusWithInterface = new QueryBusWithInterface($messageBus);

$product = $queryBus->dispatch($query); // Returns: Product
$product2 = $queryBus->execute($query); // Returns: Product
$product3 = $queryBusWithInterface->dispatch($query); // Returns: Product
// Without the feature all above query bus results would be default 'mixed'.
```

###  Health Score

80

—

ExcellentBetter than 100% of packages

Maintenance91

Actively maintained with recent releases

Popularity75

Solid adoption and visibility

Community57

Growing community involvement

Maturity86

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Recently: every ~8 days

Total

147

Last Release

81d ago

Major Versions

1.4.12 → 2.0.02024-11-06

1.4.13 → 2.0.12025-01-04

1.4.14 → 2.0.32025-03-19

1.4.15 → 2.0.42025-03-28

1.4.16 → 2.0.82025-09-07

PHP version history (4 changes)0.10PHP ^7.1

0.12.7PHP ^7.1 || ^8.0

1.2.0PHP ^7.2 || ^8.0

2.0.0PHP ^7.4 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/258cf2d2422f7e9ac5f7e1bb7a331f3fb717a11e51de7a3de2d6025507bd63cf?d=identicon)[ondrejmirtes](/maintainers/ondrejmirtes)

---

Top Contributors

[![ondrejmirtes](https://avatars.githubusercontent.com/u/104888?v=4)](https://github.com/ondrejmirtes "ondrejmirtes (157 commits)")[![lookyman](https://avatars.githubusercontent.com/u/3863468?v=4)](https://github.com/lookyman "lookyman (100 commits)")[![VincentLanglet](https://avatars.githubusercontent.com/u/9052536?v=4)](https://github.com/VincentLanglet "VincentLanglet (32 commits)")[![renovate[bot]](https://avatars.githubusercontent.com/in/2740?v=4)](https://github.com/renovate[bot] "renovate[bot] (19 commits)")[![renovate-bot](https://avatars.githubusercontent.com/u/25180681?v=4)](https://github.com/renovate-bot "renovate-bot (10 commits)")[![ruudk](https://avatars.githubusercontent.com/u/104180?v=4)](https://github.com/ruudk "ruudk (10 commits)")[![stof](https://avatars.githubusercontent.com/u/439401?v=4)](https://github.com/stof "stof (9 commits)")[![pplotka](https://avatars.githubusercontent.com/u/1835375?v=4)](https://github.com/pplotka "pplotka (9 commits)")[![mzk](https://avatars.githubusercontent.com/u/382475?v=4)](https://github.com/mzk "mzk (7 commits)")[![enumag](https://avatars.githubusercontent.com/u/539462?v=4)](https://github.com/enumag "enumag (6 commits)")[![staabm](https://avatars.githubusercontent.com/u/120441?v=4)](https://github.com/staabm "staabm (4 commits)")[![jeroennoten](https://avatars.githubusercontent.com/u/4370753?v=4)](https://github.com/jeroennoten "jeroennoten (4 commits)")[![ossinkine](https://avatars.githubusercontent.com/u/2588533?v=4)](https://github.com/ossinkine "ossinkine (4 commits)")[![Kocal](https://avatars.githubusercontent.com/u/2103975?v=4)](https://github.com/Kocal "Kocal (4 commits)")[![mitelg](https://avatars.githubusercontent.com/u/6985627?v=4)](https://github.com/mitelg "mitelg (3 commits)")[![localheinz](https://avatars.githubusercontent.com/u/605483?v=4)](https://github.com/localheinz "localheinz (3 commits)")[![fluffycondor](https://avatars.githubusercontent.com/u/62219548?v=4)](https://github.com/fluffycondor "fluffycondor (3 commits)")[![hxv](https://avatars.githubusercontent.com/u/367131?v=4)](https://github.com/hxv "hxv (3 commits)")[![bnowak](https://avatars.githubusercontent.com/u/5451843?v=4)](https://github.com/bnowak "bnowak (3 commits)")[![Khartir](https://avatars.githubusercontent.com/u/5592420?v=4)](https://github.com/Khartir "Khartir (3 commits)")

---

Tags

phpphp7phpstanstatic-analysisstatic-code-analysissymfonytestingstatic analysis

###  Code Quality

TestsPHPUnit

Type Coverage Yes

### Embed Badge

![Health badge](/badges/phpstan-phpstan-symfony/health.svg)

```
[![Health](https://phpackages.com/badges/phpstan-phpstan-symfony/health.svg)](https://phpackages.com/packages/phpstan-phpstan-symfony)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[phpstan/phpstan-doctrine

Doctrine extensions for PHPStan

66766.6M1.1k](/packages/phpstan-phpstan-doctrine)[phpstan/phpstan-strict-rules

Extra strict and opinionated rules for PHPStan

69661.6M3.9k](/packages/phpstan-phpstan-strict-rules)[phpstan/phpstan-phpunit

PHPUnit extensions and rules for PHPStan

529102.1M8.6k](/packages/phpstan-phpstan-phpunit)[spaze/phpstan-disallowed-calls

PHPStan rules to detect disallowed method &amp; function calls, constant, namespace, attribute, property &amp; superglobal usages, with powerful rules to re-allow a call or a usage in places where it should be allowed.

33320.0M375](/packages/spaze-phpstan-disallowed-calls)[phpstan/phpstan-deprecation-rules

PHPStan rules for detecting usage of deprecated classes, methods, properties, constants and traits.

44979.0M6.4k](/packages/phpstan-phpstan-deprecation-rules)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
