
phpstan-fixer
Fix PHPStan static analysis errors by adding type annotations and PHPDocs. Use when encountering PHPStan errors, type mismatches, missing type hints, or static analysis failures. Never ignores errors without user approval.
- Installs
- 113
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/marcelorodrigo/agent-skills --skill phpstan-fixer- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads phpstan-fixer automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
PHPStan Error Fixer
Fix PHPStan static analysis errors through proper type annotations, PHPDocs, and code improvements. This skill teaches agents how to resolve errors without suppressing them, respecting the project's configured strictness level.
Core Principles
- Never suppress errors as first resort — Fix the root cause with proper types and annotations
- Respect user configuration — Never modify
phpstan.neonsettings (level, paths, parameters) - No silent ignoring — Never add
ignoreErrorsto config without explicit user approval - Context-aware fixes — Understand the project type (Laravel, Symfony, vanilla PHP) before proposing solutions
- Ask before ignoring — If a legitimate ignore is needed, explain why and get user approval first
- Don't fix third-party code — Never modify files in
vendor/. Use stub files instead to override wrong types
Workflow
Step 1: Understand the Project Context
Before fixing errors, identify the project type:
# Check for Laravel
grep laravel/framework composer.json
# Check for Symfony
grep symfony/symfony composer.json
# Check for PHPStan extensions
grep phpstan composer.json
# Read PHPStan config
cat phpstan.neon
# Check project guidelines
cat AGENTS.md
Key information to extract:
- PHPStan level (0-10, or max)
- Installed PHPStan extensions (larastan, phpstan-strict-rules, etc.)
- Framework-specific helpers (Laravel IDE Helper, Symfony plugin)
- Project-specific type conventions
Step 2: Analyze the Error
PHPStan errors have this structure:
------ ----------------------------------------------
Line /path/to/File.php
------ ----------------------------------------------
42 Parameter $user of method foo() has invalid
type App\User.
💡 Identifier: parameter.type
------ ----------------------------------------------
Extract:
- Error identifier (e.g.,
parameter.type,missingType.return) - Error location (file, line number)
- Context (what's the code trying to do?)
Step 3: Apply the Right Fix
Use the error identifier to determine the fix strategy:
Step 4: Verify the Fix
After applying fixes, run PHPStan again to confirm:
vendor/bin/phpstan analyse
Important:
- If new errors appear, the fix may have been incorrect. Re-analyze the error and try a different approach.
- If the same error persists, the fix wasn't applied correctly. Double-check the code.
- If errors are resolved, mark the fix as successful and move to the next error.
Common Error Fixes
Type-Related Errors
missingType.parameter — Missing parameter type
Error:
Parameter $name has no type specified.
Fix — Add native type:
// Before
function greet($name) {
return "Hello, $name";
}
// After
function greet(string $name): string {
return "Hello, $name";
}
Fix — Use PHPDoc for complex types:
// Before
function processUsers($users) { ... }
// After
/**
* @param array<int, User> $users
*/
function processUsers(array $users): void { ... }
missingType.return — Missing return type
Error:
Method foo() has no return type specified.
Fix — Add native return type:
// Before
public function getUser() {
return $this->user;
}
// After
public function getUser(): User {
return $this->user;
}
Fix — Use PHPDoc for union/intersection types:
// Before
public function findUser($id) { ... }
// After
/**
* @return User|null
*/
public function findUser(int $id): ?User { ... }
argument.type — Wrong argument type
Error:
Parameter #1 $id of method find() expects int, string given.
Fix — Cast the argument:
// Before
$user = $repository->find($request->input('id'));
// After
$user = $repository->find((int) $request->input('id'));
Fix — Narrow the type earlier:
// Better approach
$id = $request->integer('id'); // Laravel helper
$user = $repository->find($id);
return.type — Wrong return type
Error:
Method foo() should return User but returns User|null.
Fix — Adjust return type:
// Before
public function getUser(): User {
return $this->user ?? null;
}
// After
public function getUser(): ?User {
return $this->user ?? null;
}
Fix — Ensure non-null with assertion:
public function getUser(): User {
assert($this->user !== null);
return $this->user;
}
Property Errors
property.notFound — Undefined property access
Error:
Access to an undefined property User::$name.
Fix — Add property declaration:
class User {
private string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
Fix — Document magic property:
/**
* @property string $name
*/
class User {
public function __get($key) { ... }
}
Fix (Laravel) — Use IDE Helper:
# Generate PHPDocs for Eloquent models
php artisan ide-helper:models
property.onlyWritten — Property written but never read
Error:
Property User::$name is never read, only written.
Fix — Remove unused property or add getter:
// If truly unused, remove it
// If needed, add usage:
public function getName(): string {
return $this->name;
}
Method Errors
method.notFound — Undefined method call
Error:
Call to an undefined method App\User::getFullName().
Fix — Add method:
class User {
public function getFullName(): string {
return $this->first_name . ' ' . $this->last_name;
}
}
Fix — Document magic method:
/**
* @method string getFullName()
*/
class User {
public function __call($method, $args) { ... }
}
Fix (Laravel) — Add to @mixin for query builders:
/**
* @mixin \Illuminate\Database\Eloquent\Builder
*/
class User extends Model { ... }
Array/Offset Errors
offsetAccess.notFound — Undefined array offset
Error:
Offset 'email' does not exist on array.
Fix — Use array shape PHPDoc:
/**
* @param array{email: string, name: string} $data
*/
function createUser(array $data): void {
echo $data['email']; // PHPStan knows this exists
}
Fix — Add existence check:
if (isset($data['email'])) {
echo $data['email'];
}
Fix — Use null coalescing:
$email = $data['email'] ?? 'default@example.com';
Generics Errors
missingType.generics — Missing generic type
Error:
Class Collection has @template T but does not specify it.
Fix — Specify generic type in PHPDoc:
// Before
/** @var Collection $users */
$users = User::all();
// After
/** @var Collection<int, User> $users */
$users = User::all();
Fix (Laravel) — Use IDE Helper stubs for collections.
Dead Code Errors
deadCode.unreachable — Unreachable code
Error:
Unreachable statement - code above always terminates.
Fix — Remove dead code:
// Before
function foo() {
return true;
echo "This never runs"; // Error
}
// After
function foo() {
return true;
}
identical.alwaysTrue / identical.alwaysFalse — Condition is always true/false
Error:
Strict comparison using === between int and string will always evaluate to false.
Fix — Remove useless condition or fix type:
// Before
if ($id === '123') { ... } // $id is int
// After
if ($id === 123) { ... }
Framework-Specific Fixes
Laravel
Install Larastan for Laravel-aware analysis:
composer require --dev larastan/larastan
Check phpstan.neon includes Larastan (ask user to add if missing):
includes:
- vendor/larastan/larastan/extension.neon
Common Laravel fixes:
// Eloquent relationships - use @property PHPDoc
/**
* @property-read \Illuminate\Database\Eloquent\Collection<int, Post> $posts
*/
class User extends Model {
public function posts() {
return $this->hasMany(Post::class);
}
}
// Collections - specify generic types
/** @var \Illuminate\Support\Collection<int, User> $users */
$users = User::all();
// Request input - use typed helpers
$id = $request->integer('id'); // Not $request->input('id')
$email = $request->string('email')->toString();
Symfony
Install Symfony PHPStan extension:
composer require --dev phpstan/phpstan-symfony
Check phpstan.neon includes Symfony extension (ask user to add if missing):
includes:
- vendor/phpstan/phpstan-symfony/extension.neon
parameters:
symfony:
containerXmlPath: var/cache/dev/App_KernelDevDebugContainer.xml
Common Symfony fixes:
// Service container - use proper type hints
public function __construct(
private UserRepository $userRepository, // Not mixed
) {}
// Forms - type the data
/** @var array{email: string, password: string} $data */
$data = $form->getData();
When Ignoring is Acceptable (Last Resort)
Sometimes a legitimate ignore is needed. Always ask the user first using the Question tool:
Step 1: Explain the situation
I found a PHPStan error that cannot be easily fixed:
Error: [describe error]
Location: [file:line]
Reason: [explain why it can't be fixed]
Step 2: Use Question tool to get user choice
Use the Question tool with these options:
- Header: "PHPStan Error Resolution"
- Question: "How would you like to handle this error?"
- Options:
1. "Use @phpstan-ignore with comment" - description: "Add inline ignore with explanation (recommended for third-party type issues)"
2. "Add to baseline" - description: "Generate baseline file (recommended for legacy code migration)"
3. "Refactor code" - description: "Modify code to satisfy PHPStan (most robust but may require significant changes)"
4. "Skip for now" - description: "Leave unfixed and continue with other errors"
Example Question tool usage:
{
"questions": [{
"header": "PHPStan Error Resolution",
"question": "File src/Service.php:42 has argument type mismatch with third-party API. How should I handle this?",
"options": [
{
"label": "Use @phpstan-ignore (Recommended)",
"description": "Add inline ignore with explanation"
},
{
"label": "Add to baseline",
"description": "Include in baseline file for tracking"
},
{
"label": "Refactor code",
"description": "Modify to satisfy PHPStan"
},
{
"label": "Skip for now",
"description": "Continue with other errors"
}
]
}]
}
Valid reasons for ignoring:
- Third-party library with wrong types (and no stub file available)
- Reflection-based code that's correct but PHPStan can't understand
- Complex business logic that's type-safe at runtime but not provably so statically
- Temporary during large refactoring (use baseline)
How to ignore (if approved):
// Inline ignore with explanation
/** @phpstan-ignore argument.type (API returns string|int, we handle both) */
$result = $api->getValue();
// Baseline for legacy code
vendor/bin/phpstan analyse --generate-baseline
Never do this without approval:
# Don't add this to phpstan.neon without user consent
parameters:
ignoreErrors:
- '#.*#' # NEVER
Debugging Types
Use \PHPStan\dumpType() to see what PHPStan thinks:
$user = User::find($id);
\PHPStan\dumpType($user); // Reports: App\User|null
// Remove before committing!
Troubleshooting
PHPStan doesn't recognize a valid type
Check:
- Is the class autoloadable? (
composer dump-autoload) - Does PHPStan scan the file? (Check
pathsinphpstan.neon) - Is there a typo in the namespace?
Type inference doesn't work
Check:
- Are you using inline
@vartoo much? (Fix at source instead) - Is the function/method return type specified?
- Are you using dynamic features PHPStan can't analyze?
Laravel magic methods not recognized
Install and run:
composer require --dev barryvdh/laravel-ide-helper
php artisan ide-helper:generate
php artisan ide-helper:models --write
php artisan ide-helper:meta
Error Identifier Reference
Full list: https://phpstan.org/error-identifiers
Most common categories:
argument.*— Function/method argument issuesreturn.*— Return type mismatchesmissingType.*— Missing type declarationsproperty.*— Property access/declaration issuesmethod.*— Method call issuesoffsetAccess.*— Array/ArrayAccess issuesclass.*— Class inheritance/usage issuesdeadCode.*— Unreachable codeidentical.*/equal.*— Comparison issues
Resources
FAQ
What does the phpstan-fixer skill do?
Fix PHPStan static analysis errors by adding type annotations and PHPDocs. Use when encountering PHPStan errors, type mismatches, missing type hints, or static analysis failures. Never ignores errors without user approval.
How do I install phpstan-fixer?
Run npx skills add https://github.com/marcelorodrigo/agent-skills --skill phpstan-fixer in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/phpstan-fixer/ (personal) or .claude/skills/phpstan-fixer/ (project).
Which AI agents can use phpstan-fixer?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is phpstan-fixer safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains phpstan-fixer?
It is published by marcelorodrigo in marcelorodrigo/agent-skills. It has 113 recorded installs.
More from marcelorodrigo/agent-skills
filament-pro
marcelorodrigo/agent-skills
Build Laravel admin panels with Filament v5. Use for creating resources, forms, tables, widgets, and testing admin interfaces with Livewire v4.
conventional-commit
marcelorodrigo/agent-skills
Create conventional commit messages following best conventions. Use when committing code changes, writing commit messages, or formatting git history. Follows conventional commits specification.
create-pr
marcelorodrigo/agent-skills
Create Pull Requests following best conventions. Use when opening PRs, writing PR descriptions, or preparing changes for review.
spring-boot-testing
marcelorodrigo/agent-skills
Open the skill to read its SKILL.md instructions.
Popular ai & agents skills
google-agents-cli-publish
google/agents-cli
This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).
google-agents-cli-eval
google/agents-cli
This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).
skill-creator
anthropics/skills
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
codex-pet
prime-skills/runcomfy-agent-skills
Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.
full-output-enforcement
leonxlnx/taste-skill
Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.
executing-plans
obra/superpowers
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available