From 2fc2cba098e58821bc38c63cc216e4deee2eef00 Mon Sep 17 00:00:00 2001 From: Jean-Luc Herren Date: Wed, 30 Jun 2021 21:33:04 +0200 Subject: [PATCH] Add return type extension for strval() --- conf/config.neon | 5 +++ .../Php/StrvalFunctionReturnTypeExtension.php | 33 +++++++++++++++++++ .../Analyser/NodeScopeResolverTest.php | 1 + tests/PHPStan/Analyser/data/strval.php | 19 +++++++++++ 4 files changed, 58 insertions(+) create mode 100644 src/Type/Php/StrvalFunctionReturnTypeExtension.php create mode 100644 tests/PHPStan/Analyser/data/strval.php diff --git a/conf/config.neon b/conf/config.neon index aa13516293..6ae19bb2db 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -1397,6 +1397,11 @@ services: tags: - phpstan.broker.dynamicFunctionReturnTypeExtension + - + class: PHPStan\Type\Php\StrvalFunctionReturnTypeExtension + tags: + - phpstan.broker.dynamicFunctionReturnTypeExtension + - class: PHPStan\Type\Php\StrWordCountFunctionDynamicReturnTypeExtension tags: diff --git a/src/Type/Php/StrvalFunctionReturnTypeExtension.php b/src/Type/Php/StrvalFunctionReturnTypeExtension.php new file mode 100644 index 0000000000..391003efcb --- /dev/null +++ b/src/Type/Php/StrvalFunctionReturnTypeExtension.php @@ -0,0 +1,33 @@ +getName() === 'strval'; + } + + public function getTypeFromFunctionCall( + FunctionReflection $functionReflection, + FuncCall $functionCall, + Scope $scope + ): Type + { + if (count($functionCall->args) === 0) { + return new NullType(); + } + $argType = $scope->getType($functionCall->args[0]->value); + return $argType->toString(); + } + +} diff --git a/tests/PHPStan/Analyser/NodeScopeResolverTest.php b/tests/PHPStan/Analyser/NodeScopeResolverTest.php index 19a7405266..5bfb578ccf 100644 --- a/tests/PHPStan/Analyser/NodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/NodeScopeResolverTest.php @@ -430,6 +430,7 @@ public function dataFileAsserts(): iterable yield from $this->gatherAssertTypes(__DIR__ . '/data/closure-types.php'); yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-5219.php'); + yield from $this->gatherAssertTypes(__DIR__ . '/data/strval.php'); } /** diff --git a/tests/PHPStan/Analyser/data/strval.php b/tests/PHPStan/Analyser/data/strval.php new file mode 100644 index 0000000000..04689cbcb8 --- /dev/null +++ b/tests/PHPStan/Analyser/data/strval.php @@ -0,0 +1,19 @@ + $class + */ +function test(string $class) +{ + assertType('\'foo\'', strval('foo')); + assertType('\'\'', strval(null)); + assertType('\'\'|\'1\'', strval(rand(0, 1) === 0)); + assertType('string&numeric', strval(rand())); + assertType('string&numeric', strval(rand() * 0.1)); + assertType('string&numeric', strval(strval(rand()))); + assertType('class-string', strval($class)); +}