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.20(2w ago)79475.7M↓24.4%101[61 issues](https://github.com/phpstan/phpstan-symfony/issues)[12 PRs](https://github.com/phpstan/phpstan-symfony/pulls)20MITPHPPHP ^7.4 || ^8.0CI passing

Since Jun 21Pushed 6d ago9 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 2d ago

READMEChangelog (10)Dependencies (80)Versions (164)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

82

—

ExcellentBetter than 100% of packages

Maintenance97

Actively maintained with recent releases

Popularity75

Solid adoption and visibility

Community58

Growing community involvement

Maturity87

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 ~10 days

Total

152

Last Release

11d 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://avatars.githubusercontent.com/u/104888?v=4)[Ondřej Mirtes](/maintainers/ondrejmirtes)[@ondrejmirtes](https://github.com/ondrejmirtes)

---

Top Contributors

[![ondrejmirtes](https://avatars.githubusercontent.com/u/104888?v=4)](https://github.com/ondrejmirtes "ondrejmirtes (160 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] (23 commits)")[![ruudk](https://avatars.githubusercontent.com/u/104180?v=4)](https://github.com/ruudk "ruudk (10 commits)")[![renovate-bot](https://avatars.githubusercontent.com/u/25180681?v=4)](https://github.com/renovate-bot "renovate-bot (10 commits)")[![pplotka](https://avatars.githubusercontent.com/u/1835375?v=4)](https://github.com/pplotka "pplotka (9 commits)")[![stof](https://avatars.githubusercontent.com/u/439401?v=4)](https://github.com/stof "stof (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)")[![Kocal](https://avatars.githubusercontent.com/u/2103975?v=4)](https://github.com/Kocal "Kocal (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)")[![staabm](https://avatars.githubusercontent.com/u/120441?v=4)](https://github.com/staabm "staabm (4 commits)")[![mitelg](https://avatars.githubusercontent.com/u/6985627?v=4)](https://github.com/mitelg "mitelg (3 commits)")[![fluffycondor](https://avatars.githubusercontent.com/u/62219548?v=4)](https://github.com/fluffycondor "fluffycondor (3 commits)")[![franmomu](https://avatars.githubusercontent.com/u/720690?v=4)](https://github.com/franmomu "franmomu (3 commits)")[![hxv](https://avatars.githubusercontent.com/u/367131?v=4)](https://github.com/hxv "hxv (3 commits)")[![xificurk](https://avatars.githubusercontent.com/u/117465?v=4)](https://github.com/xificurk "xificurk (3 commits)")[![bnowak](https://avatars.githubusercontent.com/u/5451843?v=4)](https://github.com/bnowak "bnowak (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.5k55.4M8.4k](/packages/larastan-larastan)[phpstan/phpstan-doctrine

Doctrine extensions for PHPStan

67272.8M1.4k](/packages/phpstan-phpstan-doctrine)[shipmonk/dead-code-detector

Dead code detector to find unused PHP code via PHPStan extension. Can automatically remove dead PHP code. Supports libraries like Symfony, Doctrine, PHPUnit etc. Detects dead cycles. Can detect dead code that is tested.

4853.5M91](/packages/shipmonk-dead-code-detector)[phpstan/phpstan-strict-rules

Extra strict and opinionated rules for PHPStan

70370.0M5.3k](/packages/phpstan-phpstan-strict-rules)[phpstan/phpstan-phpunit

PHPUnit extensions and rules for PHPStan

533113.2M11.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.

33422.6M550](/packages/spaze-phpstan-disallowed-calls)

PHPackages © 2026

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