PHPStan extensions that infer Pest closure $this type from configurable test-path mappings.
Pest binds test closures at runtime, while PHPStan analyzes code statically.
Without extra help, closure $this is commonly inferred as PHPUnit\Framework\TestCase, which can produce false positives in Pest suites.
composer require --dev odinns/phpstan-pest-thisAdd the extension to your PHPStan config:
includes:
- vendor/odinns/phpstan-pest-this/extension.neonConfigure how file paths map to Pest base test case classes:
parameters:
pestClosureThisTypeMap:
-
pathContains: '/tests/Feature/'
class: Tests\Feature\TestCase
-
pathContains: '/tests/Unit/'
class: Tests\Unit\TestCasepathContains is a substring match against the analyzed file path. The first matching mapping wins.
- Function calls:
it(...),test(...),beforeEach(...),afterEach(...) - Fluent hooks:
uses(...)->beforeEach(...),uses(...)->afterEach(...)
If your base test case has protected assertion helpers, PHPStan may flag visibility errors from Pest closures. Use the included generator to create a static-analysis-only proxy class with public wrappers.
After installation:
vendor/bin/generate-pest-proxy.php \
--source="Tests\\Feature\\TestCase" \
--target="tests/PHPStan/PestFeatureTestCase.php" \
--namespace="Tests\\PHPStan" \
--class="PestFeatureTestCase"While developing this package locally:
php tools/generate-pest-proxy.php \
--source="Tests\\Feature\\TestCase" \
--target="tests/PHPStan/PestFeatureTestCase.php" \
--namespace="Tests\\PHPStan" \
--class="PestFeatureTestCase"Then map the relevant directory to the generated proxy:
parameters:
pestClosureThisTypeMap:
-
pathContains: '/tests/Feature/'
class: Tests\PHPStan\PestFeatureTestCaseThis proxy only affects static analysis. It does not change Pest runtime behavior.
- The extension resolves closure
$thistype only. - It does not infer dynamic properties automatically; declare those on your test case/traits.
- Mapping is path-substring based, so very broad patterns can match unintentionally.
- No effect in analysis: confirm
extension.neonis included in your PHPStan config. - Wrong inferred class: ensure mapping order is specific to broad (first match wins).
- Generator not found: use
vendor/bin/generate-pest-proxy.phpafter install orphp tools/generate-pest-proxy.phpin this repository.
MIT