NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
Packagist
Packagist, #861 most downloaded on Packagist
Set of Symplify rules, type extensions and error formatter for PHPStan
Latest stable
14.19.3
Last release 1 months ago
23 Oct 2026
Release timing varies
gaps range from 9 days to 5 months
Some releases are documented
notes for 33 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
6 years old
482 releases · first in 2020
Drag across the ruler to compare, or tap a release to open it.
CommandMustHaveAsCommandAttributeRule now runs only when symfony/console is a direct require dependency
CommandMustHaveAsCommandAttributeRule now runs only when symfony/console is a direct require dependency (#381)
A require-dev only entry, or no entry at all, is ignored. Projects that pull Symfony Console transitively or just for development are no longer forced to add #[AsCommand].
Run CommandMustHaveAsCommandAttributeRule only when composer.json requires symfony/console , so projects pulling console only transitively are no long
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Skip "static::" const fetch overridden by child class in ForbiddenSta…
Skip "static::" const fetch overridden by child class in ForbiddenSta…
A batch of new rules - Doctrine Collection typing, repository return types, Symfony controller actions, nullable getters and mocked return types - plu
A batch of new rules - Doctrine Collection typing, repository return types, Symfony controller actions, nullable getters and mocked return types - plus two new rule-set groups you can toggle.
modern and collections groupsTwo new toggleable rule sets, both enabled by default (#360, #363):
parameters:
symplify:
# enabled by default
modern: true
collections: true
modern groups trait, reference, dynamic-name and foreach-ception rules.collections groups the Doctrine Collection typing rules below.Collection typing rulesFour new rules keep Doctrine Collection usage strictly typed (#363).
CollectionGetterMustReturnCollectionRule - getter of a to-many association must return Collection:
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Table]
#[ORM\Entity]
class Product
{
#[ORM\OneToMany(targetEntity: Item::class, mappedBy: 'product')]
private $items;
- public function getItems()
+ public function getItems(): Collection
{
return $this->items;
}
}
CollectionReturnMustHaveGenericDocblockRule, CollectionParamMustHaveGenericDocblockRule, CollectionPropertyMustHaveGenericDocblockRule - no bare Collection, always a generic docblock:
use Doctrine\Common\Collections\Collection;
+/** @var Collection<int, Item> */
private Collection $items;
+/** @param Collection<int, Item> $items */
public function setItems(Collection $items): void
{
}
+/** @return Collection<int, Item> */
public function getItems(): Collection
{
}
RepositoryMethodMustHaveReturnTypeRulePublic repository methods must declare a return type (#363):
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
final class ProductRepository extends ServiceEntityRepository
{
- public function findActive()
+ public function findActive(): array
{
return $this->findBy(['active' => true]);
}
}
NullablePropertyGetterMustReturnNullableRuleGetter of a nullable property must return a nullable type (#363):
private ?string $name = null;
-public function getName(): string
+public function getName(): ?string
{
return $this->name;
}
NoReadonlyApiParamRuleAn @api param may be swapped via reflection in tests, so it must not be readonly (#363):
/**
* @param string $service @api
*/
public function __construct(
- private readonly string $service,
+ private string $service,
) {
}
NoPublicNonActionMethodInControllerRuleControllers expose only route actions; helpers stay protected/private (#363):
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
final class ProductController extends AbstractController
{
#[Route('/products')]
public function list(): Response
{
// ...
}
- public function helper()
+ private function helper()
{
}
}
MockedMethodReturnMustMatchNativeTypeRulewillReturn() value must match the mocked method's native return type (#363):
class SomeObject
{
public function getName(): string
{
return '';
}
}
use PHPUnit\Framework\MockObject\MockObject;
public function run(SomeObject&MockObject $mock): void
{
- $mock->method('getName')->willReturn(123);
+ $mock->method('getName')->willReturn('name');
}
PreferGenericTemplateOnSameUnionTypeRule (rector)When a param and return share the same class-type union, add a @template to narrow the return to the passed type (#349):
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
+/**
+ * @template TNode as ClassMethod|Function_
+ * @param TNode $node
+ * @return TNode
+ */
public function process(ClassMethod|Function_ $node): ClassMethod|Function_
{
return $node;
}
<br>
TestCase reflection in NoAssertFuncCallInTestsRule (#361)#[AsDoctrineListener] in NoListenerWithoutContractRule (#358)ForbiddenArrayMethodCallRule (#357)RequireQueryBuilderOnRepositoryRule (#355)NoAssertFuncCallInTestsRule (#356)FormTypeClassNameRule to naming set (#354)curl_* and array_walk from forbidden functions (#353)CommandMustHaveAsCommandAttributeRule (#351)ForbiddenNodeRule (#346, #347)<br>
ExplicitExpectsMockMethodRule as too specific (#364)NoMockOnlyTestRule as not relevant to check (#365)NoRepositoryCallInDataFixtureRule (#362)NoDuplicateNonRepeatableAttributeRule (#359)A batch of trait/Laravel false-positive fixes, plus looser forbidden functions.
A batch of trait/Laravel false-positive fixes, plus looser forbidden functions.
RequireQueryBuilderOnRepositoryRule (#355)NoAssertFuncCallInTestsRule (#356)CommandMustHaveAsCommandAttributeRule (#351)FormTypeClassNameRule to the naming set (#354)curl_* and array_walk from forbidden functions (#353)Add PreferGenericTemplateOnSameUnionTypeRule
Add PreferGenericTemplateOnSameUnionTypeRule (#349)
Flags a method whose param and return share the same class-type union, e.g. (A|B $node): A|B|null. Such a method usually returns the passed node, so a @template generic narrows the return to the passed type. Registered in the rector-rules set.
Restore optional ForbiddenNodeRule
Rules now run on PHP 7.4+, dependencies trimmed down, ForbiddenNodeRule split into dedicated rules, plus a batch of Symfony false-positive fixes.
Rules now run on PHP 7.4+, dependencies trimmed down, ForbiddenNodeRule split into dedicated rules, plus a batch of Symfony false-positive fixes.
The ruleset now supports PHP 7.4 as minimum version, so it runs on legacy projects too - PHPStan itself supports 7.4+ (#338):
"require": {
"php": ">=7.4"
}
Source is downgraded to 7.4 syntax; dev tooling stays on 8.x.
ForbiddenTraitRule and ForbiddenSwitchRuleThe generic ForbiddenNodeRule is replaced with two focused rules - ForbiddenTraitRule and ForbiddenSwitchRule (#342).
nette/utils and webmozart/assert are replaced with entropy and native PHP (#337).
<br>
NoNullableServiceInConstructorRule (#335)NoNullableServiceInConstructorRule (#333)Dto namespace in NoNullableServiceInConstructorRule (#325)NoListenerWithoutContractRule (#334)SingleArgEventDispatchRule (#323)Attributes namespace in RequireAttributeNamespaceRule (#329)CheckRequiredInterfaceInContractNamespaceRule (#328)ForbiddenStaticClassConstFetchRule (#324)ForbiddenMultipleClassLikeInOneFileRule (#322)<br>
PreferInlineTraitRule and its collectors (#344)NoProtectedClassStmtRule (#343)All rule sets are now auto-loaded via phpstan/extension-installer - no includes: needed, just toggle them with a parameter.
All rule sets are now auto-loaded via phpstan/extension-installer - no includes: needed, just toggle them with a parameter.
Code complexity, configurable, static, Symfony, Symfony config, Doctrine and PHPUnit sets are now registered in extra.phpstan.includes and gated by a symplify.* parameter (#319):
parameters:
symplify:
# enabled by default
naming: true
complexity: true
configurable: true
static: true
symfony: true
symfonyConfig: true
doctrine: true
phpunit: true
# disabled by default
mocks: false
ctor: false
rector-rules.neon stays opt-in.
⚠️ Drop manual includes of these sets (and symplify-rules.neon) from your phpstan.neon - PHPStan reports duplicated includes.
<br>
Symfony\Component\Mailer\Transport in PreferInterfaceInConstructorRule (#320)Rule sets are now toggleable from a single symplify parameter, 4 too-narrow Symfony rules are gone, and a batch of false positives is fixed across Sym
Rule sets are now toggleable from a single symplify parameter, 4 too-narrow Symfony rules are gone, and a batch of false positives is fixed across Symfony, Doctrine, PHPUnit and the ctor rules.
Naming, complexity, configurable and static sets are now auto-loaded via phpstan/extension-installer and gated by a parameter - all on by default, so no behavior change on upgrade (#301, #304):
parameters:
symplify:
naming: false
complexity: false
configurable: false
static: false
RequireExceptionNamespaceRule, RequireAttributeNamespaceRule and CheckRequiredInterfaceInContractNamespaceRule moved from static-rules.neon to naming-rules.neon.
⚠️ naming-rules.neon is auto-loaded now - drop its manual include from your phpstan.neon to avoid double registration.
<br>
NoFindTaggedServiceIdsCallRule context-aware - skip when foreach reads tag attributes, e.g. $tags[0]['alias'] (#317)NoFindTaggedServiceIdsCallRule in test classes (#309)SingleArgEventDispatchRule (#310)#[AsDoctrineListener] attribute in NoDoctrineListenerWithoutContractRule (#318)RequireQueryBuilderOnRepositoryRule to repository classes only (#306)RequireQueryBuilderOnRepositoryRule (#312)NoAssertFuncCallInTestsRule (#311)NewOverSettersRule - skip Doctrine entities with #[ORM\Entity] (#307), controllers (#313) and test classes (#314), add regression test for setter in loop (#316)NoReferenceRule false positive when parent class is not first in its file (#292), thanks @SanderMuller<br>
NoRequiredOutsideClassRule, too narrow (#315)RequiredOnlyInAbstractRule, does not fit project context (#308)PreferAutowireAttributeOverConfigParamRule, too opinionated (#303)NoAbstractControllerConstructorRule, too strict (#302)[symfony] Handle brace-glob string exclude('../{A,B}') in AlreadyRegisteredAutodiscoveryServiceRule - fixes false positives on services excluded via a
exclude('../{A,B}') in AlreadyRegisteredAutodiscoveryServiceRule - fixes false positives on services excluded via a single glob string (#300)NoGetRepositoryOutsideServiceRule: guard empty args on getRepository() (#298)RequireInvokableControllerRule, low value (#299)exclude('../{A,B}') in AlreadyRegisteredAutodiscoveryServiceRule - fixes false positives on services excluded via a single glob string (#300)NoGetRepositoryOutsideServiceRule: guard empty args on getRepository() (#298)<br>
RequireInvokableControllerRule, low value (#299)Patch release, all refinements to existing rules plus one rule removal.
Patch release, all refinements to existing rules plus one rule removal.
Type suffix (#297)A form type class may now end in either Type or FormType. Previously only FormType was accepted, which clashed with the common Symfony SomethingType convention.
A single-parameter attribute no longer needs a named argument. With one param the positional value is unambiguous, so the name adds nothing.
// now allowed
#[Route('/home')]self/static (#294)A setter returning self or static is a deliberate fluent interface, not the accidental return the rule targets, so it is left alone.
Removed - low value in practice.
Fixes a PHPStan internal error in NoReferenceRule on classes whose ancestor exposes a magic method matching the analysed method name (e.g. Doctrine fi
Fixes a PHPStan internal error in NoReferenceRule on classes whose ancestor exposes a magic method matching the analysed method name (e.g. Doctrine findBy* finders on ObjectRepository). See #293.
5 new rules extracted from a real Symfony/Doctrine app — 2 Doctrine mapping rules, 3 Symfony PHP-config-closure rules.
5 new rules extracted from a real Symfony/Doctrine app — 2 Doctrine mapping rules, 3 Symfony PHP-config-closure rules.
Full set install:
includes:
- vendor/symplify/phpstan-rules/config/symfony-rules.neon
- vendor/symplify/phpstan-rules/config/symfony-config-rules.neon
- vendor/symplify/phpstan-rules/config/doctrine-rules.neon
- vendor/symplify/phpstan-rules/config/static-rules.neon
- vendor/symplify/phpstan-rules/config/code-complexity-rules.neon
A Doctrine association attribute must reference its target entity as a class constant, not a string.
// ❌
#[ManyToOne(targetEntity: 'App\Entity\Category')]
// ✅
#[ManyToOne(targetEntity: Category::class)]
A Doctrine entity is hydrated via reflection without the constructor, so it must not be a readonly class. An entity is recognized by an #[ORM\Entity] attribute or a public static loadMetadata() method.
// ❌
#[ORM\Entity]
final readonly class Product {}
// ✅
#[ORM\Entity]
final class Product {}
A container definition fetch that names a class by a plain string should use the class constant instead. A real class name is flagged; a service id string is left alone.
// ❌
$container->getDefinition('App\Helper\ColumnSchemaHelper');
// ✅
$container->getDefinition(ColumnSchemaHelper::class);
In a PHP config closure, a setter injection wired by hand with ->call('setX', [service(...)]) should be a #[Required] attribute on the setter, so autowiring calls it. Only a setXxx() method fed a service() is reported; a container parameter or a non-setter call stays.
// ❌
$services->set(SomeService::class)
->call('setRepository', [service(SomeRepository::class)]);
// ✅
#[Required]
public function setRepository(SomeRepository $someRepository): void
{
$this->someRepository = $someRepository;
}
When a PHP config closure's defaults() uses autoconfigure(), a ->tag() that autoconfiguration already adds by interface (console.command, form.type, kernel.event_subscriber, security.voter, twig.extension, validator.constraint_validator) is redundant. Only a tag with no attributes of its own is reported.
$services->defaults()->autoconfigure();
// ❌
$services->set(SomeSubscriber::class)
->tag('kernel.event_subscriber');
// ✅
$services->set(SomeSubscriber::class);
The rule no longer flags nullable constructor params in classes that are plainly data holders, not services. A class whose namespace contains \Entity\
Patch release.
The rule no longer flags nullable constructor params in classes that are plainly data holders, not services. A class whose namespace contains \Entity\, \Event\, \DTO\, \Message\, \DAO\, \Token\, \Exception\, \Helper\, \ValueObject\, \Form\Type\ or \Badge\ is skipped whole — their constructors carry nullable values (events, DTOs, tokens, exceptions, helpers, form types, security badges), not container services.
The existing skips stay: abstract classes, Throwable/DateTimeInterface values, a same-typed non-nullable sibling param, and anonymous classes.
No consumer-side ignoreErrors needed for those namespaces anymore.
A batch of 9 new rules extracted from a real Symfony/Doctrine app, plus a CI bugfix.
A batch of 9 new rules extracted from a real Symfony/Doctrine app, plus a CI bugfix.
Full set install:
includes:
- vendor/symplify/phpstan-rules/config/symfony-rules.neon
- vendor/symplify/phpstan-rules/config/symfony-config-rules.neon
- vendor/symplify/phpstan-rules/config/static-rules.neon
- vendor/symplify/phpstan-rules/config/code-complexity-rules.neon
A class extending Command must declare #[AsCommand].
// ❌
final class ReportCommand extends Command {}
// ✅
#[AsCommand('app:report')]
final class ReportCommand extends Command {}
A class extending Constraint must declare #[\Attribute], so it works as a property attribute.
// ❌
final class UniqueEmail extends Constraint {}
// ✅
#[\Attribute]
final class UniqueEmail extends Constraint {}
A constructor dependency typed as a concrete Symfony/Doctrine class that has a same-named *Interface should use the interface (keeps decoration open).
// ❌
public function __construct(private Router $router) {}
// ✅
public function __construct(private RouterInterface $router) {}
A constructor service must not be nullable - the container always provides it. Nullable stays allowed on abstract classes and on non-services (scalars, arrays, ?Throwable $previous, date value objects).
// ❌
public function __construct(private readonly ?SomeService $someService) {}
// ✅
public function __construct(private readonly SomeService $someService) {}
A service injected in __construct() / an autowire*() method must not be passed to another method of the same class - that method has its own constructor and can inject it directly.
// ❌
public function run(): void
{
$this->handle($this->userHelper);
}
// ✅ inject UserHelper in the constructor, then
public function run(): void
{
$this->handle();
}
In a Symfony PHP config closure, when an alias points a string id at a class, reference the service by that class instead of the string.
$services->alias('some.helper', SomeHelper::class);
// ❌
->args([service('some.helper')]);
// ✅
->args([service(SomeHelper::class)]);
An attribute repeated on the same class/method/property must declare \Attribute::IS_REPEATABLE.
// ❌
#[SomeAttribute]
#[SomeAttribute]
private string $name;
$this->a = $this->b keeps the same service under two names - use the original directly.
// ❌
$this->repository = $this->someRepository;
A method returning a packed keyed array of 2-3 named values should declare its shape.
// ❌
public function run(): array
{
return ['name' => $name, 'age' => $age];
}
// ✅
/** @return array{name: string, age: int} */
public function run(): array
{
return ['name' => $name, 'age' => $age];
}
<br>
Rector skip path so StringClassNameToClassConstantRector no longer rewrites the intentional class-name strings in src/Rules/Enum (this had turned the Rector CI job red). #286CommandMustHaveAsCommandAttributeRule and ConstraintMustHaveAttributeRule now bail out when the framework class (AsCommand, Constraint) is not installed in the analysed project - no false positive without that Symfony component. #286Only flag a cheap guard for hoisting when the expensive-call anchor merely captures the value (assignment) or bails on it (pure bail guard). An anchor
Only flag a cheap guard for hoisting when the expensive-call anchor merely
captures the value (assignment) or bails on it (pure bail guard). An anchor with
its own side effects - an attribute-writing block, or a bare call statement that
mutates a variable by-reference inside a closure - is unsafe to hoist past, since
the nodes the guard bails out on would lose that side effect. Fixes false
positives on DowngradeSubstrFalsyRector and TypeWillReturnCallableArrowFunctionRector.
Claude-Session: https://claude.ai/code/session_01Na4eYvNqa2pdhZrBXbegrv
Ported from rector-src: flags a cheap early-return guard (isName, count, in_array) placed after an expensive analysis call (getType, isObjectType, ...
Ported from rector-src: flags a cheap early-return guard (isName, count, in_array)
placed after an expensive analysis call (getType, isObjectType, ...) inside a Rector
rule, where the cheap guard could bail out first and skip the costly analysis.
Claude-Session: https://claude.ai/code/session_01Na4eYvNqa2pdhZrBXbegrv
[Rector] Skip refactor() delegating REMOVE_NODE to helper methods
[Rector] Skip refactor() delegating REMOVE_NODE to helper methods (#279)
Skip refactor() delegating REMOVE_NODE to helper methods in NoIntegerRefactorReturnRule
Skip refactor() delegating REMOVE_NODE to helper methods in NoIntegerRefactorReturnRule (#279)
`NoMissnamedDocTagRule` — no longer flags a constant whose docblock merely *mentions* @return/@param inside prose. The constant check now requires the
NoMissnamedDocTagRule — no longer flags a constant whose docblock merely mentions @return/@param inside prose. The constant check now requires the tag at the start of a docblock line (* @tag), matching the existing method/property checks. Real misnamed tags are still reported.// now skipped — @return is part of the sentence, not a tag
/**
* Using 10-level array @return docblocks makes code very hard to read,
* lets limit it to reasonable level
*/
private const int MAX_NESTING = 3;
// still reported
/**
* @return string
*/
private const NAME = 'value';
Full changelog: https://github.com/symplify/phpstan-rules/compare/14.12.1...14.12.2
`PhpUpgradeDowngradeRegisteredInSetRule` — skip rules implementing Rector\Configuration\Deprecation\Contract\DeprecatedInterface. Deprecated rules are…
PhpUpgradeDowngradeRegisteredInSetRule — skip rules implementing Rector\Configuration\Deprecation\Contract\DeprecatedInterface. Deprecated rules are not registered in config sets, so they no longer trigger the "Register ... to phpXX.php config set" error.
NoIntegerRefactorReturnRule — also inspect a bare int refactor() return type (previously only Node|int union types were checked). NodeVisitor::REMOVE_NODE stays allowed.
// now reported — was silently skipped before
public function refactor(Node $node): int
{
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}
// allowed
public function refactor(Node $node): int
{
return NodeVisitor::REMOVE_NODE;
}
Full changelog: https://github.com/symplify/phpstan-rules/compare/14.12.0...14.12.1
Config parameters are now nested under the `symplify` vendor key, following convention. Update your phpstan.neon accordingly:
symplify vendor key, following convention. Update your phpstan.neon accordingly: parameters:
- symfonyReturnType: true
- laravelReturnType: true
- pathStrings: true
+ symplify:
+ symfonyReturnType: true
+ laravelReturnType: true
+ pathStrings: true
maximumIgnoredErrorCount feature has been removed. Drop it from your config: parameters:
- maximumIgnoredErrorCount: 12
symplify/phpstan-extensions had only a few classes, so it now lives here. This brings:
symplify/phpstan-extensions into this package (#270)symplify/phpstan-extensions had only a few classes, so it now lives here. This brings:
config/phpstan-extensions.neon, all opt-in, off by default):
Container::get($id) resolved to the $id type, and Finder SplFileInfo::getRealPath() resolved to stringContainer::make($id) resolved to the $id typegetcwd() / dirname() / realpath() resolved to stringSymplifyErrorFormatter — a compact error formatter, usable via errorFormat: symplifyNewOverSettersRule ported from tomasvotruba/ctor — opt-in via ctor: true (#267)rector/mockstan — opt-in via mocks: true (#268)| Parameter | Default | What it enables |
|---|---|---|
ctor |
false |
NewOverSettersRule + its collector — flags new followed by setter calls that should be constructor arguments (#267) |
mocks |
false |
PHPUnit mock rules from rector/mockstan (#268) |
symfonyReturnType |
false |
Symfony Container::get() and Finder SplFileInfo::getRealPath() return type extensions (#270) |
laravelReturnType |
false |
Laravel Container::make() return type extension (#270) |
pathStrings |
false |
getcwd() / dirname() / realpath() always-string return type extension (#270) |
phpstan.neonAll of the above ship in the package and are auto-loaded by phpstan/extension-installer —
you only flip the parameters. The topic rule sets (Doctrine, naming, Symfony, …) stay opt-in
via includes:.
# phpstan.neon
includes:
# opt-in topic rule sets (optional)
- vendor/symplify/phpstan-rules/config/symplify-rules.neon
- vendor/symplify/phpstan-rules/config/naming-rules.neon
- vendor/symplify/phpstan-rules/config/doctrine-rules.neon
- vendor/symplify/phpstan-rules/config/symfony-rules.neon
parameters:
# opt-in rules
ctor: true # NewOverSettersRule
mocks: true # PHPUnit mock rules
# opt-in return type extensions
symfonyReturnType: true # Container::get() + Finder SplFileInfo::getRealPath()
laravelReturnType: true # Container::make()
pathStrings: true # getcwd()/dirname()/realpath() => string
Run with the bundled error formatter:
vendor/bin/phpstan analyse --error-format symplify
CLAUDE.md with project metadata (#269)Full Changelog: https://github.com/symplify/phpstan-rules/compare/14.10.0...14.11.0
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
release PHP 7.4 downgraded
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
This release is a summary of 14.6.0...14.6.33, so you can have idea what is new, thanks to release notification.
This release is a summary of 14.6.0...14.6.33, so you can have idea what is new, thanks to release notification.
This release introduces numerous new PHPStan rules, focusing on Symfony, Doctrine, and PHPUnit, with contributions from new community members enhancing the project's functionality.
<br>
It also introduced new standalone set for Symfony PHP configs:
includes:
- vendor/symplify/phpstan-rules/config/symfony-config-rules.neon
<br>
Each rule includes simple PHP code snippets, marked with :x: for non-compliant code and :+1: for compliant code.
<br>
NoGetInControllerRule in https://github.com/symplify/phpstan-rules/pull/158class SomeController
{
public function __invoke()
{
$this->get('some_service');
}
}
:x:
class SomeController
{
public function __invoke(SomeService $someService)
{
$someService->run();
}
}
:+1:
<br>
NoGetInCommandRule in https://github.com/symplify/phpstan-rules/pull/184class SomeCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->get('some_service');
return 0;
}
}
:x:
class SomeCommand extends Command
{
public function __construct(private SomeService $someService)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->someService->run();
return 0;
}
}
:+1:
<br>
NoRoutingPrefixRule in https://github.com/symplify/phpstan-rules/pull/172#[Route('/api/')]
class SomeController
{
#[Route('/something')]
public function __invoke()
{
}
}
:x:
class SomeController
{
#[Route('/api/something')]
public function __invoke()
{
}
}
:+1:
<br>
NoClassLevelRouteRule in https://github.com/symplify/phpstan-rules/pull/173#[Route('/some')]
class SomeController
{
public function __invoke()
{
}
}
:x:
class SomeController
{
#[Route('/some')]
public function __invoke()
{
}
}
:+1:
<br>
NoFindTaggedServiceIdsCallRule in https://github.com/symplify/phpstan-rules/pull/174class SomeClass
{
public function __construct(ContainerBuilder $containerBuilder)
{
$containerBuilder->findTaggedServiceIds('some_tag');
}
}
:x:
class SomeClass
{
public function __construct(ContainerBuilder $containerBuilder)
{
$containerBuilder->getServiceIds();
}
}
:+1:
<br>
NoRouteTrailingSlashPathRule in https://github.com/symplify/phpstan-rules/pull/176class SomeController
{
#[Route('/some/')]
public function __invoke()
{
}
}
:x:
class SomeController
{
#[Route('/some')]
public function __invoke()
{
}
}
:+1:
<br>
FormTypeClassNameRule to require clear naming for form types in https://github.com/symplify/phpstan-rules/pull/169class UserForm extends AbstractType
{
}
:x:
class UserType extends AbstractType
{
}
:+1:
<br>
RouteGenerateControllerClassRequireNameRule in https://github.com/symplify/phpstan-rules/pull/180$this->generateUrl(SomeController::class);
:x:
$this->generateUrl('some_route_name');
:+1:
<br>
RequiredOnlyInAbstractRule in https://github.com/symplify/phpstan-rules/pull/164class SomeService
{
#[Required]
public function setSomeDependency()
{
}
}
:x:
abstract class SomeService
{
#[Required]
public function setSomeDependency()
{
}
}
:+1:
<br>
NoConstructorAndRequiredTogetherRule in https://github.com/symplify/phpstan-rules/pull/168class SomeService
{
public function __construct()
{
}
#[Required]
public function setSomeDependency()
{
}
}
:x:
class SomeService
{
#[Required]
public function seteters
{
}
}
:+1:
<br>
SingleRequiredMethodRule to spot multiple @required methods in Symfony projects in https://github.com/symplify/phpstan-rules/pull/163class SomeService
{
#[Required]
public function setFirst()
{
}
#[Required]
public function setSecond()
{
}
}
:x:
class SomeService
{
#[Required]
public function setFirst()
{
}
}
:+1:
<br>
ServicesExcludedDirectoryMustExistRule in https://github.com/symplify/phpstan-rules/pull/202use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $configurator): void {
$services = $configurator->serivces();
$services->load('App\\', __DIR__ . '/../src')
->exclude([__DIR__ . '/this-path-does-not-exist']);
};
:x:
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $configurator): void {
$services = $configurator->services();
$services->load('App\\', __DIR__ . '/../src')
->exclude([__DIR__ . '/../src/ValueObject']);
};
:+1:
<br>
NoBundleResourceConfigRule in https://github.com/symplify/phpstan-rules/pull/203services:
resource: '../src/Bundle/SomeBundle/*'
:x:
services:
resource: '../src/App/*'
:+1:
<br>
AlreadyRegisteredAutodiscoveryServiceRule in https://github.com/symplify/phpstan-rules/pull/204use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->load('App\\', __DIR__ . '/../src')
->exclude([__DIR__ . '/src/Services']);
$services->set(SomeService::class);
};
:x:
<br>
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->load('App\\', __DIR__ . '/../src')
->exclude([__DIR__ . '/src/Services']);
};
:+1:
<br>
TaggedIteratorOverRepeatedServiceCallRule in https://github.com/symplify/phpstan-rules/pull/209class SomeClass
{
public function __construct(ContainerBuilder $containerBuilder)
{
$containerBuilder->getDefinition('some_service')->addTag('some_tag');
$containerBuilder->getDefinition('some_service')->addTag('some_tag');
}
}
:x:
class SomeClass
{
public function __construct(ContainerBuilder $containerBuilder)
{
$containerBuilder->getDefinition('some_service')->addTag('some_tag');
}
}
:+1:
<br>
NoDuplicateArg(s)AutowireByTypeRule and NoServiceSameNameSetClassRule in https://github.com/symplify/phpstan-rules/pull/210use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SomeService::class)
->args([
ref(SomeService::class),
]);
};
:x:
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SomeService::class);
};
:+1:
<br>
RequireIsGrantedEnumRule in https://github.com/symplify/phpstan-rules/pull/213use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_USER')]
class SomeController
{
}
:x:
<br>
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(SomeEnum::ROLE_USER)]
class SomeController
{
}
:+1:
<br>
NoBareAndSecurityIsGrantedContentsRule in https://github.com/symplify/phpstan-rules/pull/214Instead of using one long "and" condition join, split into multiple standalone #[IsGranted] attributes
rules:
- Symplify\PHPStanRules\Rules\Symfony\NoBareAndSecurityIsGrantedContentsRule
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('has_role(ROLE_USER) and has_role(ROLE_ADMIN)')]
class SomeController
{
}
:x:
<br>
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_USER')]
#[IsGranted('ROLE_ADMIN')]
class SomeController
{
}
:+1:
<br>
PreferAutowireAttributeOverConfigParamRule in https://github.com/symplify/phpstan-rules/pull/215services:
App\SomeService:
arguments:
$someParam: '%some_param%'
:x:
class SomeService
{
#[Autowire('%some_param%')]
private string $someParam;
}
:+1:
<br>
RequireQueryBuilderOnRepositoryRule in https://github.com/symplify/phpstan-rules/pull/158class SomeRepository extends EntityRepository
{
public function findSomething()
{
$this->getEntityManager()->createQuery('SELECT ...');
}
}
:x:
class SomeRepository extends EntityRepository
{
public function findSomething()
{
$this->createQueryBuilder('e')->select('...');
}
}
:+1:
<br>
NoGetRepositoryOnServiceRepositoryEntityRule in https://github.com/symplify/phpstan-rules/pull/182class SomeService
{
public function __construct(EntityManagerInterface $entityManager)
{
$entityManager->getRepository(SomeEntity::class);
}
}
:x:
class SomeService
{
public function __construct(SomeRepository $someRepository)
{
$someRepository->findAll();
}
}
:+1:
<br>
RequiredDoctrineServiceRepositoryParentRule in https://github.com/symplify/phpstan-rules/pull/208class SomeRepository
{
public function findSomething()
{
}
}
:x:
class SomeRepository extends EntityRepository
{
public function findSomething()
{
}
}
:+1:
<br>
NoListenerWithoutContractRule in https://github.com/symplify/phpstan-rules/pull/201class SomeListener
{
public function __invoke(SomeEvent $event)
{
}
}
:x:
class SomeListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [SomeEvent::class => 'onEvent'];
}
public function onEvent(SomeEvent $event)
{
}
}
:+1:
<br>
NoMockObjectAndRealObjectPropertyRule in https://github.com/symplify/phpstan-rules/pull/170class SomeTest extends TestCase
{
private SomeService $someService;
private MockObject $someServiceMock;
protected function setUp(): void
{
$this->someServiceMock = $this->createMock(SomeService::class);
}
}
:x:
class SomeTest extends TestCase
{
private MockObject $someServiceMock;
protected function setUp(): void
{
$this->someServiceMock = $this->createMock(SomeService::class);
}
}
:+1:
<br>
NoAssertFuncCallInTestsRule in https://github.com/symplify/phpstan-rules/pull/175class SomeTest extends TestCase
{
public function testSomething()
{
assert($this->someService->run());
}
}
:x:
class SomeTest extends TestCase
{
public function testSomething()
{
$this->assertTrue($this->someService->run());
}
}
:+1:
<br>
NoValueObjectInServiceConstructorRule in https://github.com/symplify/phpstan-rules/pull/152class SomeService
{
public function __construct(ValueObject $valueObject)
{
}
}
:x:
class SomeService
{
public function __construct(ServiceDependency $serviceDependency)
{
}
}
:+1:
<br>
ForbiddenNewArgumentRule in https://github.com/symplify/phpstan-rules/pull/158class SomeClass
{
public function run()
{
new SomeArgument();
}
}
:x:
class SomeClass
{
public function run(SomeArgument $someArgument)
{
}
}
:+1:
<br>
MaximumIgnoredErrorCountRule enabled in configuration in https://github.com/symplify/phpstan-rules/pull/162parameters:
ignoreErrors:
- '#Some error 1#'
- '#Some error 2#'
- '#Some error 3#'
:x:
parameters:
ignoreErrors:
- '#Some error 1#'
:+1:
<br>
StringFileAbsolutePathExistsRule in https://github.com/symplify/phpstan-rules/pull/171class SomeClass
{
public function run()
{
require_once '/non/existent/path.php';
}
}
:x:
class SomeClass
{
public function run()
{
require_once '/existing/path.php';
}
}
:+1:
<br>
NoJustPropertyAssignRule in https://github.com/symplify/phpstan-rules/pull/177class SomeClass
{
public function run($value)
{
$this->value = $value;
}
}
:x:
class SomeClass
{
public function run($value)
{
$this->value = $this->processValue($value);
}
}
:+1:
<br>
NoProtectedClassStmtRule in https://github.com/symplify/phpstan-rules/pull/185protected class SomeClass
{
}
:x:
class SomeClass
{
}
:+1:
<br>
NoArrayMapWithArrayCallableRule in https://github.com/symplify/phpstan-rules/pull/217$values = array_map(['SomeClass', 'method'], $items);
:x:
$values = array_map(fn($item) => SomeClass::method($item), $items);
:+1:
<br>
Add 15 PHPStan rules from Handyman, mostly Symfony, Doctrine, and PHPUnit related in https://github.com/symplify/phpstan-rules/pull/153
class SomeClass
{
public function run($value)
{
$value->call();
}
}
:x:
class SomeClass
{
public function run(SomeObject $value)
{
$value->call();
}
}
:+1:
<br>
@Myks92 made their first contribution in https://github.com/symplify/phpstan-rules/pull/190
@kkevindev made their first contribution in https://github.com/symplify/phpstan-rules/pull/205
Thanks to @staabm for git export improvements, @samsonasik for PHPStan version updates and rule refinements, @Myks92 for Doctrine-related contributions, and @kkevindev for README improvements.
Full Changelog: https://github.com/symplify/phpstan-rules/compare/14.0.0...14.6.3
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
One column per quarter.