bnf/phpstan-psr-container
PHPStan dynamic return type extension for PSR-11 ContainerInterface. Improves type inference for $container->get() so services are typed correctly during static analysis. Install via Composer and include extension.neon (or use phpstan/extension-installer).
Install the package via Composer: composer require --dev bnf/phpstan-psr-container. For seamless integration, use the phpstan/extension-installer (recommended for PHPStan 2.x+). If using manual setup, enable it in your phpstan.neon:
includes:
- vendor/bnf/phpstan-psr-container/extension.neon
No further configuration is needed for basic use. Start with running phpstan analyze—this extension now supports PHPStan 2.x (previously 1.x only). If your code uses ContainerInterface::get() or has() (e.g., Symfony, Zend, or custom PSR-11 implementations), PHPStan will infer return types more accurately. For example, get(MyService::class) will resolve to MyService instead of mixed, reducing “Method X called on mixed” errors.
/** @return MyClass */) on factory methods to improve inferred types for dynamically resolved services, especially in Symfony-like containers.@method annotations or PHPDoc @return in get()/has() methods. The extension consumes these to refine type inference—critical for non-standard containers.__invoke + container, use string-literal service IDs (e.g., MyService::class) or ::class constants for static analysis. Avoid variables (e.g., get($dynamicId)) unless annotated with @phpstan-param string $id.phpstan.neon initially (e.g., level: 5), then incrementally increase strictness. Use --exclude-analyse for legacy code until refactored.extension-installer. Example phpstan.neon for auto-install:
includes:
- vendor/phpstan/phpstan/src/Rules/*.neon
- vendor/phpstan/phpstan-extension-installer/extension.neon
composer require phpstan/phpstan:^2). Downgrade the extension to 1.0.1 if stuck on PHPStan 1.x.get($variable)) still fall back to mixed. Mitigate with:
@phpstan-param string $id on container methods.@phpstan-assert for runtime-validated IDs.get()), add a custom stub in phpstan.neon:
parameters:
container:
getReturnTypeExpr: 'string($id) ? MyService::class : mixed'
laravel-console-emulator) temporarily to isolate behavior. PHPStan 2.x’s improved extension system may resolve some conflicts automatically./** @phpstan-type ServiceAlias string */
const ServiceAlias = 'app.my_service';
Or import types via @phpstan-import-type.// In a factory or service:
/** @phpstan-ignore-next-line */
$container->has('unreachable_service');
Or use @phpstan-assert for conditional checks.How can I help you explore Laravel packages today?