jbboehr / phpstan-laravel-validation
Laravel Validation extension for PHPStan
Installs: 8 895
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 2
Forks: 1
Open Issues: 9
Type:phpstan-extension
Requires
- php: ^8.0
- nikic/php-parser: ^4.15 || ^5.1
- phpstan/phpstan: ^1.9
Requires (Dev)
- brick/varexporter: ^0.3.7
- illuminate/http: ^9.45 || ^10.0
- illuminate/validation: ^9.45 || ^10.0
- laravel/framework: ^9.45 || ^10.0
- laravel/laravel: ^9.45 || ^10.0
- phpstan/phpstan-php-parser: ^1.1
- phpstan/phpstan-phpunit: *
- phpstan/phpstan-strict-rules: ^1.4
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.6.0
This package is auto-updated.
Last update: 2024-11-13 00:02:31 UTC
README
Explanation
If the rules given to a laravel validator are a constant expression, then the shape of the array returned by \Illuminate\Validation\Validator::validated()
is known at compile-time, and can be statically analyzed.
$request = new \Illuminate\Http\Request(); $data = \Illuminate\Support\Facades\Validator::make($request->all(), [ 'person.*.email' => 'required|email|unique:users', 'person.*.first_name' => 'required|string', 'person.*.age' => 'required|integer|string', ])->validated(); \PHPStan\dumpType($data); // array{person: array<int|string, array{email: non-empty-string, first_name: string, age: numeric-string}>} $data = $request->validate([ 'person.*.email' => 'required|email|unique:users', 'person.*.first_name' => 'required|string', 'person.*.age' => 'required|integer|string', ]); \PHPStan\dumpType($data); // array{person: array<int|string, array{email: non-empty-string, first_name: string, age: numeric-string}>}
If the input data does not match the rules array, an \Illuminate\Validation\ValidationException
is thrown, thus preserving type safety.
Installation
To use this extension, require it in Composer:
composer require --dev jbboehr/phpstan-laravel-validation
If you also install phpstan/extension-installer then you're all set!
Manual installation
If you don't want to use phpstan/extension-installer
, include extension.neon
in your project's PHPStan config:
includes: - vendor/jbboehr/phpstan-laravel-validation/extension.neon
Caveats
- Laravel's validation does not cast anything, so, for example,
numeric
produces the type unionint|float|numeric-string
. If you know it will always be a string, you can refine the type by usingnumeric|string
and get a plainnumeric-string
. - Wildcards must be indexed by integer and can't be mixed with non-wildcard rules.
- Custom validation rules, implicit rules, and enums are not currently supported.
License
This project is licensed under the AGPL v3+ License - see the LICENSE.md file for details.