Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Crafting Custom PHPStan Rules for Symfony Apps

Ondřej Mirtes
December 07, 2024
19

Crafting Custom PHPStan Rules for Symfony Apps

Static analysis tools like PHPStan have become essential for PHP developers, and Symfony projects can greatly benefit from custom rules tailored to their specific needs. In this talk, I will guide Symfony developers through the process of writing custom PHPStan rules to enforce project-specific standards and catch domain-specific bugs, and freeing up valuable time by automating repetitive code review tasks.

Ondřej Mirtes

December 07, 2024
Tweet

Transcript

  1. Cra ft ing Custom PHPStan Rules for Symfony Apps Ondřej

    Mirtes SymfonyCon, December 6th 2024
  2. Motivation for custom rules Make code reviews easier Prevent bugs

    and production incidents Achieve consistency & quality
  3. Abstract syntax tree (AST) $this->foo && self::bar() BooleanAnd PropertyFetch StaticCall

    Variable ("this") "foo" "self" "bar" le f right var name class name
  4. Writing custom rules interface Rule { /** * @return string

    Class implementing \PhpParser\Node */ public function getNodeType(): string; /** * @param \PhpParser\Node $node * @param \PHPStan\Analyser\Scope $scope * @return RuleError[] errors */ public function processNode(Node $node, Scope $scope): array; }
  5. Scope getFile(): string getNamespace(): ?string isInClass(): bool getClassReflection(): ?ClassReflection isInTrait():

    bool getTraitReflection(): ?ClassReflection getFunction(): ?FunctionReflection|?MethodReflection getType(Expr $expr): Type isInExpressionAssign(Expr $expr): bool canAccessProperty(PropertyReflection $property): bool canCallMethod(MethodReflection $methodReflection): bool
  6. Ideas for custom rules Require named arguments for attributes: ✅

    #[Autowire(service: 'app.foo.bar')] ❌ #[Autowire('app.foo.bar')]