Skip to content

PHPStan Rules 14.15

Choose a tag to compare

@TomasVotruba TomasVotruba released this 21 Sep 11:23
· 79 commits to main since this release

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

🎉 New rules

NoStringTargetEntityRule

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)]

NoReadonlyEntityClassRule

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 {}

PreferClassInDefinitionFetchRule

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);

NoServiceSetterCallRule

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;
}

NoAutoconfiguredServiceTagRule

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);