From 7a66cb6eda85703811c7dce472355e036d70c144 Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Sat, 5 Mar 2022 12:56:34 +0100 Subject: [PATCH] Do not add null to a template type for a default parameter value null --- src/Reflection/Php/PhpParameterReflection.php | 7 ++- .../Analyser/NodeScopeResolverTest.php | 1 + tests/PHPStan/Analyser/data/bug-6584.php | 44 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 tests/PHPStan/Analyser/data/bug-6584.php diff --git a/src/Reflection/Php/PhpParameterReflection.php b/src/Reflection/Php/PhpParameterReflection.php index 63be44cf3c..414a7722f0 100644 --- a/src/Reflection/Php/PhpParameterReflection.php +++ b/src/Reflection/Php/PhpParameterReflection.php @@ -6,6 +6,7 @@ use PHPStan\Reflection\PassedByReference; use PHPStan\Type\ConstantTypeHelper; use PHPStan\Type\MixedType; +use PHPStan\Type\NullType; use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; use PHPStan\Type\TypehintHelper; @@ -43,7 +44,11 @@ public function getType(): Type $phpDocType = $this->phpDocType; if ($phpDocType !== null) { try { - if ($this->reflection->isDefaultValueAvailable() && $this->reflection->getDefaultValue() === null) { + if ( + $this->reflection->isDefaultValueAvailable() + && $this->reflection->getDefaultValue() === null + && (new NullType())->isSuperTypeOf($phpDocType)->no() + ) { $phpDocType = TypeCombinator::addNull($phpDocType); } } catch (Throwable) { diff --git a/tests/PHPStan/Analyser/NodeScopeResolverTest.php b/tests/PHPStan/Analyser/NodeScopeResolverTest.php index 88a0da3a53..2c00be34fb 100644 --- a/tests/PHPStan/Analyser/NodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/NodeScopeResolverTest.php @@ -767,6 +767,7 @@ public function dataFileAsserts(): iterable yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-5668.php'); yield from $this->gatherAssertTypes(__DIR__ . '/data/generics-empty-array.php'); yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/Methods/data/bug-5757.php'); + yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6584.php'); } /** diff --git a/tests/PHPStan/Analyser/data/bug-6584.php b/tests/PHPStan/Analyser/data/bug-6584.php new file mode 100644 index 0000000000..c989a35199 --- /dev/null +++ b/tests/PHPStan/Analyser/data/bug-6584.php @@ -0,0 +1,44 @@ +same($int)); + assertType('int', $this->sameWithDefault($int)); + + assertType('int|null', $this->same($intOrNull)); + assertType('int|null', $this->sameWithDefault($intOrNull)); + + assertType('null', $this->same(null)); + assertType('null', $this->sameWithDefault(null)); + assertType('null', $this->sameWithDefault()); + } + + + /** + * @template T + * @param T $t + * @return T + */ + function same($t) { + assertType('T (method Bug6584\Foo::same(), argument)', $t); + return $t; + } + + /** + * @template T + * @param T $t + * @return T + */ + function sameWithDefault($t = null) { + assertType('T (method Bug6584\Foo::sameWithDefault(), argument)', $t); + return $t; + } + +}