SkilVaultSign inStart free

Catalogue / resolve-phpstan-errors

resolve-phpstan-errors

Older skill: source not recordedSignedFixes PHPStan static analysis findings at their root cause by adding native type declarations, PHPDoc annotations, and small code changes, then re-runs analysis to confirm each error is gone. Covers missing parameter and return types, argument and return type mismatches, unknown properties and metho…
---
name: resolve-phpstan-errors
description: >
  Fixes PHPStan static analysis findings at their root cause by adding native
  type declarations, PHPDoc annotations, and small code changes, then re-runs
  analysis to confirm each error is gone. Covers missing parameter and return
  types, argument and return type mismatches, unknown properties and methods,
  array offsets, generics, dead code, and always-true or always-false
  comparisons, plus Laravel and Symfony specifics. Use when PHPStan reports
  errors, a CI or build step fails on PHPStan output, or the user asks for
  type hints, stricter typing, or static-analysis cleanup. Not for installing
  or configuring PHPStan from scratch, raising or lowering the analysis
  level, migrating from other analysers, or debugging PHP at runtime.
license: MIT
---

Resolve PHPStan Errors

You clear PHPStan findings by correcting types and code, message by message, until a fresh analysis run is clean. Suppression exists in this skill only as a last step that the user explicitly approves.

Ground Rules

  1. Treat every finding as a symptom of a missing or wrong type; fix the cause in the code, not the report in the config.
  2. Leave phpstan.neon (and phpstan.neon.dist) alone — level, paths, parameters, and includes stay as the user set them. Propose changes in conversation instead of applying them.
  3. Never edit anything under vendor/. When a dependency ships incorrect types, offer a stub file in the project (wiring it into the config still needs the user's go-ahead).
  4. Do not install packages on your own initiative. Name the package and let the user run the install, or proceed only after they approve it in writing.
  5. Never add a catch-all suppression entry to the config that would silence every current and future message — describe that risk to the user if they ask for it rather than doing it.
  6. Work at the configured strictness level; do not loosen code just to make a report disappear.

This skill does not cover initial PHPStan setup, choosing or changing analysis levels, or migrating off other analysers — it only clears errors at the level already configured.

Step 1 — Read the Context

Before touching code, gather:

  • The PHPStan config (phpstan.neon or phpstan.neon.dist): the level and any includes.
  • composer.json require/require-dev: is phpstan/phpstan present? Framework (laravel/framework, symfony/*)? Extensions such as larastan/larastan, phpstan/phpstan-symfony, or strict-rules packages?
  • Project conventions if an AGENTS.md, CONTRIBUTING.md, or similar file exists.

Decide what flavour of PHP you are in (Laravel, Symfony, plain) — it changes which fix is idiomatic.

Step 2 — Run the Analysis and Decode Each Finding

Run vendor/bin/phpstan analyse and, for each message, extract three things:

  • The identifier printed after the light-bulb marker (for example parameter.type, missingType.return) — this is your routing key.
  • The file and line.
  • What the code is actually trying to do.

Step 3 — Match the Identifier to a Fix Family

| Identifier family | Meaning | First fix to try | |---|---|---| | missingType.* | Parameter, return value, or generic has no declared type | Add a native type; use PHPDoc for unions, array shapes, generics | | argument.* | Passed value does not match the parameter | Narrow or convert the value at the call boundary | | return.type | Returned value does not match the declaration | Correct the declaration, or guarantee the value with a guard | | property.* | Unknown, write-only, or mistyped property | Declare it, document magic access, or delete dead ones | | method.* | Call to a method PHPStan cannot see | Define the method, or annotate __call magic | | offsetAccess.* | Array/ArrayAccess key not provably present | Array-shape PHPDoc, isset, or null coalescing | | class.* | Unknown class, inheritance or instanceof problem | Check namespace and imports; refine the hierarchy | | deadCode.* | Unreachable or useless code | Delete it | | identical.*, equal.* | Comparison outcome is predetermined | Fix the operand type, or drop the branch |

The full catalogue lives at https://phpstan.org/error-identifiers — consult it for identifiers outside this table.

Step 4 — Apply the Smallest Correct Fix

Concrete recipes with new examples:

Missing parameter type. Prefer native types; reach for PHPDoc only for shapes, unions, and generics.

// Before
public function normalizeSku($sku) { return trim(strtoupper($sku)); }

// After
public function normalizeSku(string $sku): string { return trim(strtoupper($sku)); }

// Complex values go through PHPDoc
/**
 * @param array<int, Invoice> $invoices
 */
public function totalOf(array $invoices): float { /* ... */ }

Wrong argument type. Convert or narrow where the untyped value enters, not deep inside.

// Before — repository wants int, request gives string
$invoice = $this->invoices->find($request->input('invoiceId'));

// After — typed accessor (Laravel), or an explicit (int) cast elsewhere
$invoice = $this->invoices->find($request->integer('invoiceId'));

Wrong return type. Either tell the truth in the signature or prove the value.

// Before — declared Asset, but ->first() can yield null
public function currentAsset(): Asset { return $this->assets->first(); }

// After — honest signature
public function currentAsset(): ?Asset { return $this->assets->first(); }

// Or — guaranteed value
public function currentAsset(): Asset
{
    return $this->assets->first() ?? throw new RuntimeException('No asset bound');
}

Unknown property. Declare it, or document magic access.

class Subscription
{
    private Plan $plan;

    public function __construct(Plan $plan) { $this->plan = $plan; }
}

// Or, for __get magic:
/**
 * @property string $displayName
 */
class Subscription
{
    public function __get(string $key) { /* ... */ }
}

Write-only property. Remove it if nothing needs it; otherwise give it a reader such as public function plan(): Plan.

Unknown method. Implement it, or annotate the magic.

final class Customer
{
    public function initials(): string
    {
        return strtoupper(substr($this->firstName, 0, 1));
    }
}

// Or, for __call magic:
/**
 * @method string initials()
 */

Unknown array offset. Describe the shape, or defend the access.

/**
 * @param array{host: string, port: int} $dsnParts
 */
function connect(array $dsnParts): void
{
    echo $dsnParts['host']; // now provably present
}

// Or: $port = $dsnParts['port'] ?? 3306;
// Or: if (isset($dsnParts['port'])) { ... }

Missing generic. Spell out template parameters.

// Before
/** @var Collection $customers */
$customers = Customer::query()->get();

// After
/** @var Collection<int, Customer> $customers */
$customers = Customer::query()->get();

Dead code and predetermined comparisons. Delete statements after a terminal return or throw. When a strict comparison can never match because the operand is an integer written as a string (port 3306 compared against the digit string), correct the literal's type; if the condition is genuinely always true or false, remove the branch.

Step 5 — Verify and Iterate

Re-run vendor/bin/phpstan analyse after each fix or small batch.

  • The error is gone: move on.
  • The same error remains: your change did not reach the real cause — reread the code.
  • New errors appeared: your fix altered types more widely than intended — back it out and choose a narrower one.

Framework Notes

Laravel. If larastan/larastan is missing, suggest the user install it as a dev dependency and add its extension.neon to the includes — only after they agree. Typical fixes:

/**
 * @property-read \Illuminate\Database\Eloquent\Collection<int, Order> $orders
 */
class Customer extends Model
{
    public function orders() { return $this->hasMany(Order::class); }
}

/** @var \Illuminate\Support\Collection<int, Customer> $customers */

$id = $request->integer('customerId');        // instead of input()
$tag  = $request->string('tag')->toString();

For model magic that Larastan still cannot see, offer the IDE Helper generator commands (for example the artisan command that writes model PHPDocs) and wait for approval before running them.

Symfony. If phpstan/phpstan-symfony is absent, propose it the same way. Typical fixes: fully typed constructor injection instead of mixed, and an array shape on form data:

/** @var array{email: string, password: string} $credentials */
$credentials = $form->getData();

Suppression: Only After Asking

Some findings cannot be fixed honestly — a third-party signature that is genuinely wrong with no usable stub, reflection-heavy code that is safe at runtime but invisible statically, or bulk legacy debt. In those cases:

  1. Show the user the error text, its file and line, and one sentence on why a real fix is not viable.
  2. Ask them to choose, in plain text, and wait for the answer: an inline suppression with a written reason, generating a baseline, a deeper refactor, or skipping this error.
  3. Act only on the chosen option.

This skill does not include an interactive multiple-choice prompt mechanism; a plain-text question with listed options serves the same purpose.

/** @phpstan-ignore return.type (legacy SDK may yield null; every caller null-checks) */

For the baseline route — chosen by the user only — run vendor/bin/phpstan analyse --generate-baseline, then ask before adding the generated baseline file to the config's includes, since that is a config edit.

Peeking at Inferred Types

When unsure what PHPStan believes a value is, inspect it:

$plan = Plan::find($planId);
\PHPStan\dumpType($plan); // prints something like App\Models\Plan|null

Remove the dump call before finishing; it is scaffolding, never committed code.

When a Fix Does Not Take

  • "Class not found" persists: run composer dump-autoload, confirm the file sits under a path the config analyses, and check the namespace matches the directory.
  • Inference stays stuck: too many inline @var overrides is a smell — push types into signatures instead of papering over call sites.
  • Framework magic stays invisible: verify the framework extension is actually listed in the config's includes, not just installed.

---

Attribution: adapted from the phpstan-fixer skill in the MIT-licensed repository marcelorodrigo/agent-skills; same license applies here.