Skip to content

Commit

Permalink
Fix inferring template types in ClosureType
Browse files Browse the repository at this point in the history
  • Loading branch information
canvural committed Jan 13, 2022
1 parent 9d66886 commit f27f0a3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Type/ClosureType.php
Expand Up @@ -334,7 +334,7 @@ public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
return $receivedType->inferTemplateTypesOn($this);
}

if ($receivedType->isCallable()->no()) {
if ($receivedType->isCallable()->no() || ! $receivedType instanceof self) {
return TemplateTypeMap::createEmpty();
}

Expand Down
32 changes: 32 additions & 0 deletions tests/PHPStan/Analyser/data/generic-unions.php
Expand Up @@ -61,3 +61,35 @@ public function foo(
}

}

/**
*
* @template TGetDefault
* @template TKey
*
* @param TKey $key
* @param TGetDefault|(\Closure(): TGetDefault) $default
* @return TKey|TGetDefault
*/
function getWithDefault($key, $default = null)
{
if(rand(0,10) > 5) {
return $key;
}

if (is_callable($default)) {
return $default();
}

return $default;
}

assertType('int|null', getWithDefault(3));
assertType('int|string', getWithDefault(3, 'foo'));
assertType('int|string', getWithDefault(3, function () {
return 'foo';
}));
assertType('GenericUnions\Foo|int', getWithDefault(3, function () {
return new Foo;
}));
assertType('GenericUnions\Foo|int', getWithDefault(3, new Foo));

0 comments on commit f27f0a3

Please sign in to comment.