diff --git a/docs/reference.md b/docs/reference.md index d60d882..f933206 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -178,8 +178,10 @@ bootstrap files too) it does nothing. Side effect: PHPStan itself no longer sees `StaticMethodTypeSpecifyingExtension` + `TypeSpecifierAwareExtension`. Narrows variable types after `Tester\Assert` calls by mapping each assertion to an equivalent expression and delegating to `TypeSpecifier::specifyTypesInCondition()`. Supports `null`, `notNull`, `true`, `false`, -`truthy`, `falsey`, `same`, `notSame`, `type` (built-in type strings and class/interface names). -A shipped feature, not test-only. +`truthy`, `falsey`, `nan`, `same`, `notSame`, `count` (`array|Countable` with `count() === $n`), +`hasKey`/`hasNotKey` (`array_key_exists()`), `type` (built-in type strings including `list`, +class/interface names, a union of constant strings → `||` of the checks, or an object → +`instanceof` its class). A shipped feature, not test-only. ### Assets family (`MapperTypeResolver` shared service) diff --git a/readme.md b/readme.md index e2c58d5..085e976 100644 --- a/readme.md +++ b/readme.md @@ -84,7 +84,7 @@ parameters: **Subject narrowing after match** — inside `if (Strings::match($s, '#\d+#'))` the subject `$s` is narrowed (e.g. to `non-empty-string`) based on the pattern. -**Assert type narrowing** — PHPStan understands type guarantees after `Tester\Assert` calls like `notNull()`, `type()`, `true()`, etc. +**Assert type narrowing** — PHPStan understands type guarantees after `Tester\Assert` calls like `notNull()`, `type()`, `true()`, `count()`, `hasKey()`, etc. **False positive suppression** — silences known PHPStan false positives in Nette patterns (arrow functions passed as `void` callbacks, runtime type validation closures, callbacks assigned to Form event-handler properties like `$onSuccess`, `$onClick`). diff --git a/src/Tester/AssertTypeNarrowingExtension.php b/src/Tester/AssertTypeNarrowingExtension.php index ebe57dd..0c58ff5 100644 --- a/src/Tester/AssertTypeNarrowingExtension.php +++ b/src/Tester/AssertTypeNarrowingExtension.php @@ -3,7 +3,7 @@ namespace Nette\PHPStan\Tester; use PhpParser\Node\{Arg, Expr, Name}; -use PhpParser\Node\Expr\BinaryOp\{Identical, NotIdentical}; +use PhpParser\Node\Expr\BinaryOp\{BooleanAnd, BooleanOr, Identical, NotIdentical}; use PhpParser\Node\Expr\{BooleanNot, ConstFetch, FuncCall, Instanceof_, StaticCall}; use PHPStan\Analyser\{Scope, SpecifiedTypes, TypeSpecifier, TypeSpecifierAwareExtension, TypeSpecifierContext}; use PHPStan\Reflection\MethodReflection; @@ -39,11 +39,22 @@ public function isStaticMethodSupported( ): bool { $minArgs = match ($staticMethodReflection->getName()) { - 'null', 'notNull', 'true', 'false', 'truthy', 'falsey' => 1, - 'same', 'notSame', 'type' => 2, + 'null', 'notNull', 'true', 'false', 'truthy', 'falsey', 'nan' => 1, + 'same', 'notSame', 'type', 'count', 'hasKey', 'hasNotKey' => 2, default => null, }; - return $minArgs !== null && count($node->getArgs()) >= $minArgs; + if ($minArgs === null || $node->isFirstClassCallable() || count($node->getArgs()) < $minArgs) { + return false; + } + + // named arguments are left unresolved only in an invalid call + foreach (array_slice($node->getArgs(), 0, $minArgs) as $arg) { + if ($arg->unpack || $arg->name !== null) { + return false; + } + } + + return true; } @@ -62,9 +73,22 @@ public function specifyTypes( 'false' => new Identical($args[0]->value, new ConstFetch(new Name('false'))), 'truthy' => $args[0]->value, 'falsey' => new BooleanNot($args[0]->value), + 'nan' => new BooleanAnd( + new FuncCall(new Name('is_float'), [$args[0]]), + new FuncCall(new Name('is_nan'), [$args[0]]), + ), 'same' => new Identical($args[1]->value, $args[0]->value), 'notSame' => new NotIdentical($args[1]->value, $args[0]->value), 'type' => $this->createTypeExpression($scope, $args), + 'count' => new BooleanAnd( + new BooleanOr( + new FuncCall(new Name('is_array'), [$args[1]]), + new Instanceof_($args[1]->value, new Name(\Countable::class)), + ), + new Identical(new FuncCall(new Name('count'), [$args[1]]), $args[0]->value), + ), + 'hasKey' => new FuncCall(new Name('array_key_exists'), [$args[0], $args[1]]), + 'hasNotKey' => new BooleanNot(new FuncCall(new Name('array_key_exists'), [$args[0], $args[1]])), default => null, }; @@ -81,41 +105,69 @@ public function specifyTypes( /** + * Type name strings (a union of them means any of the types) or an object (instanceof its class). * @param Arg[] $args */ private function createTypeExpression(Scope $scope, array $args): ?Expr { $typeType = $scope->getType($args[0]->value); - $constantStrings = $typeType->getConstantStrings(); - - if (count($constantStrings) === 1) { - $typeName = $constantStrings[0]->getValue(); - - $func = match ($typeName) { - 'list', 'array' => 'is_array', - 'bool' => 'is_bool', - 'callable' => 'is_callable', - 'float' => 'is_float', - 'int', 'integer' => 'is_int', - 'null' => 'is_null', - 'object' => 'is_object', - 'resource' => 'is_resource', - 'scalar' => 'is_scalar', - 'string' => 'is_string', - default => null, - }; - - return $func !== null - ? new FuncCall(new Name($func), [$args[1]]) - : new Instanceof_($args[1]->value, new Name($typeName)); + $checks = []; + + if ($typeType->isObject()->yes()) { + foreach ($typeType->getObjectClassNames() as $className) { + $checks[] = new Instanceof_($args[1]->value, new Name($className)); + } + } else { + foreach ($typeType->getConstantStrings() as $constantString) { + $check = $this->createTypeNameCheck($constantString->getValue(), $args[1]); + if ($check === null) { + return null; + } + $checks[] = $check; + } } - // object argument → instanceof using its class - $classNames = $typeType->getObjectClassNames(); - if (count($classNames) === 1) { - return new Instanceof_($args[1]->value, new Name($classNames[0])); + if (!$checks) { + return null; + } + + $expression = array_shift($checks); + foreach ($checks as $check) { + $expression = new BooleanOr($expression, $check); + } + return $expression; + } + + + private function createTypeNameCheck(string $typeName, Arg $value): ?Expr + { + if ($typeName === 'list') { + return new BooleanAnd( + new FuncCall(new Name('is_array'), [$value]), + new FuncCall(new Name('array_is_list'), [$value]), + ); + } + + $func = match ($typeName) { + 'array' => 'is_array', + 'bool' => 'is_bool', + 'callable' => 'is_callable', + 'float' => 'is_float', + 'int', 'integer' => 'is_int', + 'null' => 'is_null', + 'object' => 'is_object', + 'resource' => 'is_resource', + 'scalar' => 'is_scalar', + 'string' => 'is_string', + default => null, + }; + if ($func !== null) { + return new FuncCall(new Name($func), [$value]); } - return null; + $className = ltrim($typeName, '\\'); + return $className === '' + ? null + : new Instanceof_($value->value, new Name($className)); } } diff --git a/tests/Tester/assert-type-narrowing.php b/tests/Tester/assert-type-narrowing.php index fb5824e..da1dc77 100644 --- a/tests/Tester/assert-type-narrowing.php +++ b/tests/Tester/assert-type-narrowing.php @@ -126,7 +126,7 @@ function testTypeNull(int|string|null $val): void function testTypeList(mixed $val): void { Assert::type('list', $val); - assertType('array', $val); + assertType('list', $val); } @@ -142,3 +142,121 @@ function testTypeInterface(mixed $val): void Assert::type(Countable::class, $val); assertType('Countable', $val); } + + +function testTypeLeadingBackslash(mixed $val): void +{ + Assert::type('\\stdClass', $val); + assertType('stdClass', $val); +} + + +function testTypeEmptyString(mixed $val): void +{ + Assert::type('', $val); + assertType('mixed', $val); +} + + +/** + * @param array $args + */ +function testUnpackedArguments(array $args): void +{ + Assert::null(...$args); + assertType('array', $args); + + Assert::same(...$args); + assertType('array', $args); +} + + +function testNamedArguments(mixed $val): void +{ + Assert::null(description: 'must be null', actual: $val); + assertType('null', $val); +} + + +function testUnresolvableNamedArguments(?string $description): void +{ + Assert::null(description: $description); + assertType('string|null', $description); + + Assert::same(description: $description, expected: 1); + assertType('string|null', $description); +} + + +function testTypeUnion(mixed $val): void +{ + $type = rand(0, 1) ? 'int' : 'string'; + Assert::type($type, $val); + assertType('int|string', $val); +} + + +function testTypeObjectArgument(mixed $val): void +{ + Assert::type(new stdClass, $val); + assertType('stdClass', $val); +} + + +function testNan(mixed $val): void +{ + Assert::nan($val); + assertType('float', $val); +} + + +/** + * @param string[] $one + * @param int[] $none + */ +function testCount(array $one, array $none): void +{ + Assert::count(1, $one); + assertType('non-empty-array', $one); + + Assert::count(0, $none); + assertType('false', reset($none)); +} + + +/** + * @param array $val + */ +function testCountNamedArguments(array $val): void +{ + Assert::count(value: $val, count: 1); + assertType('non-empty-array', $val); +} + + +/** + * @param array{foo?: int, bar: string} $shape + * @param array $array + */ +function testHasKey(array $shape, array $array): void +{ + Assert::hasKey('foo', $shape); + assertType('array{foo: int, bar: string}', $shape); + + Assert::hasKey('foo', $array); + assertType("non-empty-array&hasOffset('foo')", $array); +} + + +/** + * @param array{foo?: int, bar: string} $shape + * @param array $array + */ +function testHasNotKey(array $shape, array $array): void +{ + Assert::hasNotKey('foo', $shape); + assertType('array{bar: string}', $shape); + + Assert::hasNotKey('foo', $array); + assertType('array', $array); +}