hihaho / phpstan-rules
Hihaho PHPStan rules according to the guidelines
Package info
github.com/hihaho/phpstan-rules
Type:phpstan-extension
pkg:composer/hihaho/phpstan-rules
Requires
- php: ^8.3
- illuminate/database: ^12.0||^13.0
- illuminate/http: ^12.0||^13.0
- illuminate/support: ^12.0||^13.0
- phpstan/phpstan: ^2.1.8
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pao: ^1.1
- laravel/pint: ^1.21
- nikic/php-parser: ^5.4
- nunomaduro/collision: ^8.9
- orchestra/testbench: ^10.0||^11.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^12.5.22
- rector/rector: ^2.0
- rector/type-perfect: ^2.0
- sandermuller/boost-skills: ^2.4
- sandermuller/package-boost-php: ^1.0
- spatie/invade: ^2.1
- spaze/phpstan-disallowed-calls: ^4.4
- symplify/phpstan-extensions: ^12.0.1
- tomasvotruba/cognitive-complexity: ^1.0
- tomasvotruba/type-coverage: ^2.0
This package is auto-updated.
Last update: 2026-06-25 06:24:14 UTC
README
A set of PHPStan rules that enforce Hihaho's Laravel guidelines
at analyse time. They flag invade() calls in app code, facade aliases
outside Blade, stray debug helpers (dump, dd, ray, and friends)
left behind in production or test paths, and unvalidated request reads —
including FormRequest fields read outside the class's own rules().
If you want the auto-fix counterparts for class-naming and route-group
conventions, see hihaho/rector-rules.
Requirements
- PHP 8.3 or higher
- PHPStan 2.1 or higher
- Laravel 12.x or 13.x (via
illuminate/supportandilluminate/database)
Installation
composer require --dev hihaho/phpstan-rules
If you have phpstan/extension-installer,
that's it. The rules register themselves.
Without it, include the extension in your phpstan.neon:
includes: - vendor/hihaho/phpstan-rules/extension.neon
Rules
NoInvadeInAppCode
Flags invade() calls inside App\.
invade is a test helper for reaching into private state; it has no place
in production code. Also flags \Livewire\invade() in any namespace; if
you need invade, use the global one from spatie/invade.
namespace App\Services; invade($user)->privateMethod(); // reported
Identifiers: hihaho.generic.noInvadeInAppCode,
hihaho.generic.disallowedUsageOfLivewireInvade
OnlyAllowFacadeAliasInBlade
Short facade aliases belong in Blade. In PHP, use the fully qualified facade so imports stay explicit.
use Route; // reported use Illuminate\Support\Facades\Route; // fine
Identifier: hihaho.generic.onlyAllowFacadeAliasInBlade
Debug rules
Three rules that together keep debug calls out of App\ and Tests\:
| Rule | Targets | Examples |
|---|---|---|
NoDebugInNamespaceRule |
Global debug functions | dump(), dd(), ddd(), ray(), print_r(), var_dump() |
ChainedNoDebugInNamespaceRule |
Method chains on Laravel types | collect()->dump(), $builder->dd() |
StaticChainedNoDebugInNamespaceRule |
Static calls on Laravel facades | Http::dump(), Cache::dd() |
The chained and static rules use PHPStan reflection to narrow matches:
they only flag methods declared by (or proxied through) the Illuminate\
namespace, so your own domain classes with a ->dump() method stay clean.
Identifiers: hihaho.debug.noDebugIn{App,Tests},
hihaho.debug.noChainedDebugIn{App,Tests},
hihaho.debug.noStaticChainedDebugIn{App,Tests}
Request-validation rules
Four rules flag unvalidated request data. The first three flag reads from Illuminate\Http\Request; the fourth flags reading a field inside a FormRequest that the same class's rules() never validates. Use validated data instead: $request->validated(), $request->safe()->string('key'), or the array returned by $request->validate([...]).
| Rule | Targets | Identifier |
|---|---|---|
NoUnsafeRequestDataRule |
Method calls on Request / FormRequest |
hihaho.validation.noUnsafeRequestData |
NoUnsafeRequestHelperRule |
request('key') helper with a literal arg |
hihaho.validation.noUnsafeRequestHelper |
NoUnsafeRequestFacadeRule |
Static calls on Illuminate\Support\Facades\Request |
hihaho.validation.noUnsafeRequestFacade |
UnvalidatedFormRequestFieldRule |
$this->input('key') inside a FormRequest, key ∉ rules() |
hihaho.validation.unvalidatedFormRequestField |
FormRequest auto-validation runs on dispatch, but inherited readers still return the full payload including keys outside rules(), so they're flagged on FormRequest too. Chained request()->input('x') is caught by the Data rule because the receiver resolves to Request. Zero-argument request() is not flagged.
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Request as RequestFacade; final class StoreUserController { public function __invoke(Request $request): mixed { $request->input('name'); // reported (data) request('id'); // reported (helper) RequestFacade::boolean('debug'); // reported (facade) $request->safe()->string('name'); // fine return $request->validate(['name' => 'required']); } }
Reads from $this inside a Request subclass, including your own FormRequest bases, are exempted. The scope-class check walks the inheritance chain, so a custom App\Http\Requests\FormRequest extends BaseFormRequest extends Illuminate\Foundation\Http\FormRequest works without extra config. Static calls on Illuminate\Http\Request itself (e.g. Request::capture()) aren't flagged; they don't return raw input.
UnvalidatedFormRequestFieldRule covers that $this-inside-a-FormRequest exemption from the other side: it flags $this->boolean('submit_redirect') when submit_redirect is never declared in the same class's rules(). To stay high-precision it only resolves a literal return [...] array — a conditional, spread, array_merge(), returned variable, or a rules() it can't read statically makes the class opaque and skips it — and it skips any class that overrides prepareForValidation(), validationData(), or all() (including via a shared base or trait), since those rewrite the validated set. rules() declared on a base class is followed; nested keys match on their root segment, so a rule for address.street validates a read of address.
Out of scope: ArrayAccess ($request['x']), magic property access ($request->x), and Symfony InputBag property access ($request->query->get('x'), ->headers->get(), ->cookies->get()). The InputBag path is legitimate for raw header or cookie reads, but flag it in code review so it doesn't turn into a de-facto suppression channel.
Configuration
parameters: noUnsafeRequestData: namespaces: - App excludeNamespaces: - App\Providers # Laravel bootstrap (default) - App\Http\Responses # Fortify response contracts (default) # - App\Http\Resources # opt-in: accept toArray(Request) reads unsafeMethods: # full default list in extension.neon - input - all - get
App\Providers and App\Http\Responses are default-excluded because the signatures there come from the framework (RateLimiter::for(...) closures, LoginResponse::toResponse(Request)) and there's no FormRequest to route the data through. App\Http\Resources is opt-in. Whether a resource should read raw request is a team call.
UnvalidatedFormRequestFieldRule reuses noUnsafeRequestData.namespaces / excludeNamespaces and carries its own list of single-key readers under unvalidatedFormRequestField.accessors (input, get, query, post, string, str, integer, boolean, float, json, array, collect, date, enum, enums, file); the full default is in extension.neon.
Adopting on an existing codebase
First-run baselines are nonzero. Generate one and work it down over multiple PRs:
vendor/bin/phpstan analyse --generate-baseline
Patterns that will stay baselined (the rule can't help with them):
- Dynamic-key admin CRUD. Bulk-edit controllers looping over
$request->collect('fields')->each(...)with schema-driven keys. Suppress inline:// @phpstan-ignore hihaho.validation.noUnsafeRequestData $value = $request->input($field->key);
- Pre-validation framework callbacks. Already covered by the
App\Providersdefault exclusion. - Fortify response contracts. Already covered by the
App\Http\Responsesdefault exclusion. JsonResource::toArray(Request). AddApp\Http\ResourcestoexcludeNamespacesif you accept the pattern.
Safe-swap yield on the first triage runs 2-10% from field data: calls already validated inline where the flagged key is in the rules, plus FormRequest cases where the flagged key is in rules() and migrates to $request->safe()->string(...) or $request->validated(). The rest needs judgment. Your options are to introduce a FormRequest, extend existing rules to cover the flagged key, push validation upstream, or refactor the surrounding code. Plan on several PRs over weeks, not a one-time sweep.
Common traps:
- "Injected a FormRequest, so I'm safe." The rule fires when the FormRequest has no
rules()(auth-only wrappers) or has rules that don't cover the flagged key. Checkrules()before assuming it's a false positive. validated()drops keys not inrules(), nested props included. Reading$request->input('interactions.$.foo')won't migrate if onlyinteractionsis inrules(). You'll need nested rules first.- LLM agents are unreliable for bulk triage on this rule. Reliable categorization needs AST inspection that intersects
validate()rule keys with flagged keys; one adopter's agent caught 1 of 5 candidates. Use human review or a Rector pass. - Livewire and Filament projects handle input through component props and form schemas, outside these rules' node targets. A low hit count is a structural fact, not proof of cleanliness. Review
mount()and form-submit paths separately.
Rule hits in Support or utility namespaces often point at dead code. Grep the call graph before adding to the baseline; the fix may be a delete.
Convention rules
Flag a bare true/false/null literal passed positionally as the last argument of a first-party method, nullsafe-method, static, or constructor call. A positional setActive('name', false) hides what the flag means; naming it — setActive('name', active: false) — makes the call self-documenting.
| Rule | Targets | Identifier |
|---|---|---|
PositionalFlagArgumentMethodCallRule |
$obj->method(..., true) |
hihaho.conventions.positionalFlagArgument |
PositionalFlagArgumentNullsafeMethodCallRule |
$obj?->method(..., true) |
hihaho.conventions.positionalFlagArgument |
PositionalFlagArgumentStaticCallRule |
Klass::method(..., true) |
hihaho.conventions.positionalFlagArgument |
PositionalFlagArgumentConstructorRule |
new Klass(..., true) |
hihaho.conventions.positionalFlagArgument |
namespace App\Services; $toggle->setActive('name', false); // reported — name the flag: active: false $toggle?->setActive('name', false); // reported StaticFlag::toggle('name', false); // reported new Widget('name', true); // reported $toggle->setActive('name', active: false); // fine — already named
This pairs with rector-rules' FirstPartyFlagArgumentToNamedRector, which auto-fixes the flags it can resolve with bare PHPStan. Because PHPStan rules inherit the consumer's extensions, this rule flags the rest in a larastan-equipped app — including receivers (generic or inherited properties) that rector cannot resolve. rector rewrites; this rule gates.
Scope: the last argument only, and only when every argument is positional (no named or spread args); the matched parameter must be named and non-variadic. The parameter need not be bool-typed — a bare null on a ?Object or mixed parameter is opaque too, matching the convention and the rector fixer (which names any bare flag without a type check). The gate is on the resolved member's declaring class, so an App\ class inheriting a vendor method isn't flagged against vendor-declared, non-semver-stable parameter names. Callee namespaces are configurable:
parameters: positionalFlagArgument: firstPartyNamespaces: - App - Database\Factories - Tests
Param names aren't semver-stable in vendor code, so only first-party callees are flagged.
Named-argument manifest (opt-in producer)
rector-rules' NamedArgumentFromManifestRector names these flags at call sites whose receiver only resolves under larastan — the sites bare-PHPStan auto-fixers can't reach. It is inert without a JSON manifest, which this package can produce: include the opt-in extension and run analysis in your larastan-equipped project.
includes: - vendor/hihaho/phpstan-rules/named-argument-manifest.neon parameters: namedArgumentManifest: firstPartyNamespaces: - App - Database\Factories - Tests outputPath: named-arguments-manifest.json
vendor/bin/phpstan analyse then writes named-arguments-manifest.json — the same detection emitted as records ({file, line, method, argIndex, paramName, value}) instead of errors, with no CI errors raised. It is a PHPStan Collector, not an error formatter, so it is independent of the gate rules and unaffected by your baseline (baselined sites still appear in the manifest).
outputPath may be nested (e.g. .config/named-arguments-manifest.json); the parent directory is created if it does not exist.
Reflection extensions
Stubbed methods
StubbedMethodsClassReflectionExtension teaches PHPStan about instance methods that exist at
runtime but not in reflection — Faker custom providers (added via __call) and Laravel macros.
Without it, calls to these resolve to "undefined method" and have to be baselined, which also hides
genuine typos. With it, the configured methods resolve to their declared return type, and a
misspelled name (not in the configured set) still fails analysis. Statically-called methods (e.g.
facade __callStatic) are out of scope — the stubbed methods are modelled as instance methods.
It resolves nothing by default — each project declares its own methods via the stubbedMethods
parameter, a map of class name => (method name => return type):
parameters: stubbedMethods: Faker\Generator: videoTimeInMilliseconds: int validPassword: string timestampsOfVideoClicks: 'array<int, int>' Illuminate\Testing\TestResponse: assertSeeLivewire: Illuminate\Testing\TestResponse fillForm: Illuminate\Testing\TestResponse Laravel\Nova\Fields\Number: onlyOnExport: '$this'
Return types are parsed with PHPStan's type-string resolver, so any valid PHPDoc type works
(string, array<int, int>, a class name for chainable assertions, etc.). A return type of
$this, static, or self is bound to the receiver, so a stubbed fluent method (a
$this-returning macro, a chainable Nova field method) keeps its chain typed
(Number::make(…)->onlyOnExport()->sortable()) instead of widening. Stubbed methods accept any
arguments, so only the method name and its return type are modelled — argument types are not checked.
Return type extensions
Collection values()->all() list typing
CollectionListAllReturnTypeExtension types ->values()->all() on a Collection/LazyCollection
as list<TValue> instead of array<int, TValue>. Laravel types values() as static<int, TValue>
and all() as array<TKey, TValue>, neither of which carries PHPStan's list marker — so a method
declared @return list<T> is forced to wrap the chain in array_values() even though values()
already re-keyed to a list at runtime. The list type matters: a non-list array is JSON-encoded as a
JS object, silently breaking frontend consumers that expect an array.
/** @return list<int> */ public function ids(Collection $users): array { return $users->map(fn (User $user): int => $user->id)->values()->all(); // list<int>, no array_values() }
It is registered automatically — no configuration. Two guards keep it sound: detection is syntactic
(the receiver must be a direct ->values() call, so a chain split across variables is left alone
rather than guessed), and the receiver must be a Support\Collection/LazyCollection (or subclass)
— a bare Enumerable or a custom implementation with unknown key semantics is never narrowed.
Route-model binding typing
RouteBindingReturnTypeExtension types $this->route('x') / $request->route('x') as the model
bound to route parameter x, reading the actual bindings from your route-service providers. Laravel
types route() as object|string|null, so resolving a bound model normally needs an
assert($model instanceof Video) after every call — and the parameter name doesn't reveal the model
(video_id → Video). This reads Route::model('x', M::class) and Route::bind('x', fn (): M => …)
from the configured providers and returns the bound type, so the assert is no longer needed while a
wrong assignment still fails.
Configure the providers to read via the routeBindingProviders parameter — it's empty by default, so
nothing is narrowed until you list them:
parameters: routeBindingProviders: - App\Providers\RouteServiceProvider
public function handle(Request $request): void { $video = $request->route('video_id'); // Video — no assert() needed }
Scope: only a single constant-string argument is narrowed (route() with no argument, a default
argument, a dynamic name, or an unknown parameter keeps its default type); only the instance method
is covered (the Request:: facade's static form is out of scope); Route::bind() closures without a
return-type hint, and Route::model() bindings with a missing-model callback, are skipped. A bound
parameter is typed as the non-null model — matching the intent of the assert() calls it
replaces. That over-claims by dropping null when the current route lacks the parameter (an optional
{param?} segment, or shared middleware/helpers reached from routes without it), so use it for code
reached only via routes that define the parameter and keep an explicit null check where a request may
legitimately lack it.
Implicit bindings. Parameters bound implicitly (by the controller's type-hint, with no
Route::model() declaration) are resolved as a fallback by listing your route files in routeFiles:
parameters: routeFiles: - routes/web.php - routes/api.php
It reads each Route::<verb>('uri/{param}', Action) — an invokable Controller::class or a
[Controller::class, 'method'] — and types route('param') as the action parameter Laravel would
bind to it (matched by name or Str::snake(), exactly as the framework does), unioned across every
route that declares the parameter. Explicit provider bindings win over implicit ones. It is fail-safe:
closures, group-level controllers, Route::resource, non-model type-hints, and unreadable files are
skipped, leaving the default type — it never mis-types. Paths are resolved from the working directory
PHPStan runs in (your project root), so project-relative paths like routes/web.php work; the
extension parses the files statically — it does not boot your application.
Adopting this is a one-time assert-removal sweep. Once
route('x')is typed as the bound model, any existingassert($x instanceof Model)orinstanceofguard after it becomes "always true" — PHPStan reports it as a redundant condition. (This is an expression-type resolver, sotreatPhpDocTypesAsCertain: falsedoes not soften it.) Removing those now-redundant asserts is the point of the feature; expect a one-off cleanup when you first enablerouteBindingProviders. Keep only the guards on routes that may legitimately lack the parameter (the non-null caveat above).
Parameter closure type extensions
Relation-existence closure builder typing
RelationExistenceClosureBuilderParameterExtension types the closure passed to Eloquent's
relationship-existence methods (whereHas, orWhereHas, whereDoesntHave, orWhereDoesntHave,
has, orHas, doesntHave, orDoesntHave) as the related model's builder. Laravel types the
callback as Closure(Builder<TRelatedModel>), but when the relation is passed as a string PHPStan
cannot bind TRelatedModel, so it falls back to Builder<Model>. Under checkModelProperties that
makes every ->where(RelatedModel::SOME_COLUMN) inside the closure fail on valid columns.
/** @param Builder<User> $query */ public function scopeWithPublishedPosts(Builder $query): void { // $q is Builder<Post> — Post::PUBLISHED resolves instead of erroring against base Model. $query->whereHas('posts', fn (Builder $q) => $q->where(Post::STATUS, Post::PUBLISHED)); }
It is registered automatically — no configuration. The closure parameter needs no annotation (a bare
Builder hint is narrowed in place), arrow functions are preserved, dotted nested relations
('posts.comments') resolve to the last related model, and a related model with a custom builder
(HasBuilder/newEloquentBuilder()) keeps that builder type. It fails safe: when the model or
relation can't be proven (dynamic relation name, unknown relation), the default typing stands, so a
genuinely wrong column on the correct related model still fails.
Use
voidclosures, not closures that return the builder. Eloquent'sBuilder<TModel>is invariant, and Laravel types the callback's return asmixed(it's ignored at runtime — the closure constrains the query in place). Once the parameter is narrowed to the related model, a closure that returns the builder — e.g.fn ($q) => $q->where(...)orreturn $q->where(...)— reportsreturn.type: should return Builder<Model> but returns Builder<RelatedModel>. Write the callback as avoidblock instead; the return value serves no purpose:// Triggers a return.type error (returns the narrowed builder): $query->whereHas('posts', fn (Builder $q) => $q->where(Post::STATUS, Post::PUBLISHED)); // Clean — the closure constrains in place and returns nothing: $query->whereHas('posts', function (Builder $q): void { $q->where(Post::STATUS, Post::PUBLISHED); });
Testing
composer test
Before opening a PR, run the full pipeline (Pint, Rector, PHPStan, tests):
composer qa
Changelog
See CHANGELOG.md for release notes.
Contributing
See CONTRIBUTING.md.
Security
Please email security@hihaho.com instead of filing a public issue.
Credits
License
MIT. See LICENSE.md.