ย
Provides custom type extensions and error suppression rules used when analysing Nette libraries with PHPStan.
ย
Install via Composer:
composer require --dev nette/phpstan-rulesRequirements: PHP 8.1 or higher and PHPStan 2.1+.
If you use phpstan/extension-installer, the extension is registered automatically. Otherwise add to your phpstan.neon:
includes:
- vendor/nette/phpstan-rules/extension.neonย
ย
Removes |false from return types of native PHP functions and methods where false is trivial or outdated. For example, getcwd() returns string|false, but on modern systems false is unrealistic. This extension narrows it to string.
Covered functions include getcwd, json_encode, preg_match, preg_split, hash, explode, array_combine, and many more.
// Without extension: string|false
// With extension: non-empty-string
$cwd = getcwd();ย
Suppresses argument.type when an arrow function is passed to a parameter typed as Closure(): void. Arrow functions always return a value, so PHPStan reports a type mismatch even though the return value is simply discarded. This extension ignores the error for configured functions like test, testException, testNoError, Assert::exception, Assert::throws, Assert::error, and Assert::noError.
// Without extension: argument.type error
// With extension: no error
testException('listOf() & error', fn() => Expect::listOf(['a' => Expect::string()]), TypeError::class);Narrows variable types after Tester\Assert assertion calls, so PHPStan understands the type guarantees made by assertions like Assert::notNull(), Assert::type(), Assert::true(), etc.
/** @var string|null $name */
Assert::notNull($name);
// PHPStan now knows $name is string
Assert::type('int', $value);
// PHPStan now knows $value is int- Narrows the return type of
Expect::array()fromStructure|TypetoStructureorTypebased on the argument
Suppresses expr.resultUnused for the runtime type validation pattern commonly used in Nette:
/** @param string[] $items */
public function setItems(array $items): void
{
(function (string ...$items) {})(...$items);
}PHPStan normally reports the closure call result as unused. This extension recognizes the pattern (empty closure body, all parameters variadic with type hints) and ignores the error.
ย
The package also provides Nette\PHPStan\Tester\TypeAssert for testing type inference in Nette packages using Nette Tester:
use Nette\PHPStan\Tester\TypeAssert;
// Verify assertType() calls in a data file
TypeAssert::assertTypes(__DIR__ . '/data/types.php', [__DIR__ . '/../extension.neon']);
// Verify PHPStan reports no errors on a file
TypeAssert::assertNoErrors(__DIR__ . '/data/clean.php', [__DIR__ . '/../extension.neon']);The data file uses assertType() from PHPStan:
use function PHPStan\Testing\assertType;
assertType('non-empty-string', getcwd());
assertType('string', Normalizer::normalize('foo'));ย
Do you like Nette? Are you looking forward to the new features?
Thank you!
