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 c73d0db commit b981544
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Type/CallableType.php
Expand Up @@ -218,7 +218,7 @@ public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
return $receivedType->inferTemplateTypesOn($this);
}

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

Expand Down
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
72 changes: 72 additions & 0 deletions tests/PHPStan/Analyser/data/generic-unions.php
Expand Up @@ -61,3 +61,75 @@ public function foo(
}

}

class InvokableClass
{
public function __invoke(): string
{
return '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;
}

/**
*
* @template TGetDefault
* @template TKey
*
* @param TKey $key
* @param TGetDefault|(callable(): TGetDefault) $default
* @return TKey|TGetDefault
*/
function getWithDefaultCallable($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|null', getWithDefaultCallable(3));
assertType('int|string', getWithDefault(3, 'foo'));
assertType('int|string', getWithDefaultCallable(3, 'foo'));
assertType('int|string', getWithDefault(3, function () {
return 'foo';
}));
assertType('int|string', getWithDefaultCallable(3, function () {
return 'foo';
}));
assertType('GenericUnions\Foo|int', getWithDefault(3, function () {
return new Foo;
}));
assertType('GenericUnions\Foo|int', getWithDefaultCallable(3, function () {
return new Foo;
}));
assertType('GenericUnions\Foo|int', getWithDefault(3, new Foo));
assertType('GenericUnions\Foo|int', getWithDefaultCallable(3, new Foo));
assertType('int|string', getWithDefaultCallable(3, new InvokableClass));

0 comments on commit b981544

Please sign in to comment.