Installation:
composer require --dev calebdw/fakerstan --with-all-dependencies
Ensure phpstan/extension-installer is also installed to auto-load the extension.
Configuration:
Add to your phpstan.neon:
includes:
- vendor/calebdw/fakerstan/extension.neon
First Use Case:
Run PHPStan on a file using Faker (e.g., tests/Unit/UserFactoryTest.php):
phpstan analyse tests/Unit --level=5
The extension will now validate Faker method calls (e.g., fake()->name()) for type correctness.
Type-Safe Faker Usage: Use Faker methods with IDE autocompletion and PHPStan validation:
$user = User::factory()->create([
'name' => fake()->name(), // Validated as string
'email' => fake()->unique()->email(), // Validated as string
]);
Custom Faker Rules:
Extend Faker’s rules in phpstan.neon:
parameters:
fakerstan:
rules:
- method: 'fake()->safeEmail()'
returnType: 'string'
Integration with Factories: Validate factory traits or custom factories:
// tests/Unit/UserFactory.php
use FakerStan\FakerStan;
class UserFactory extends Factory
{
use FakerStan; // Auto-validates Faker calls
}
Dynamic Rules:
Use phpstan.neon to override return types for dynamic Faker calls:
parameters:
fakerstan:
dynamicRules:
- pattern: 'fake()->creditCardNumber()'
returnType: 'string'
pestphp/pest or phpunit/phpunit for seamless validation in test suites.phpstan.neon to reflect new methods:
parameters:
fakerstan:
providers:
- 'App\Providers\CustomFakerProvider'
False Positives:
fake()->method($arg)) as untyped. Use dynamicRules to whitelist them.phpstan.neon:
parameters:
fakerstan:
ignoreDynamicMethods: true
Provider Conflicts:
AppServiceProvider).Faker::extend() before running PHPStan.Nested Faker Calls:
fake()->domainName()->email()) may not resolve types correctly.dynamicRules:
parameters:
fakerstan:
dynamicRules:
- pattern: 'fake()->domainName()->email()'
returnType: 'string'
--verbose to see FakerStan’s parsed rules.includes:
- vendor/calebdw/fakerstan/extension.neon
# Disable for testing:
# includes: []
Custom Return Types:
Override return types for non-standard Faker methods via phpstan.neon:
parameters:
fakerstan:
rules:
- method: 'fake()->customMethod()'
returnType: 'App\Models\User'
Plugin System:
Use FakerStan\Extension\ExtensionInterface to create custom extensions for organization-specific Faker logic.
Performance: Exclude large test files from FakerStan checks if performance is critical:
excludes:
- tests/Feature/LargeTestSuite.php
How can I help you explore Laravel packages today?