Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/Type/Php/DsMapDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;

final class DsMapDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension
Expand Down Expand Up @@ -35,11 +37,24 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method
)->getReturnType();
}

if (! $returnType instanceof UnionType) {
return $returnType;
if ($returnType instanceof UnionType) {
$types = array_values(
array_filter(
$returnType->getTypes(),
static function (Type $type): bool {
return !$type instanceof TemplateType;
}
)
);

if (count($types) === 1) {
return $types[0];
}

return TypeCombinator::union(...$types);
}

return $returnType->getTypes()[0];
return $returnType;
}

}
36 changes: 36 additions & 0 deletions tests/PHPStan/Analyser/data/ext-ds.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,42 @@ class B

class Foo
{
/** @param Map<int, int> $a */
public function mapGet(Map $a) : void
{
assertType('int', $a->get(1));
}

/** @param Map<int, int> $a */
public function mapGetWithDefaultValue(Map $a) : void
{
assertType('int|null', $a->get(1, null));
}

/** @param Map<int, int|string> $a */
public function mapGetUnionType(Map $a) : void
{
assertType('int|string', $a->get(1));
}

/** @param Map<int, int|string> $a */
public function mapGetUnionTypeWithDefaultValue(Map $a) : void
{
assertType('int|string|null', $a->get(1, null));
}

/** @param Map<int, int|string> $a */
public function mapRemoveUnionType(Map $a) : void
{
assertType('int|string', $a->remove(1));
}

/** @param Map<int, int|string> $a */
public function mapRemoveUnionTypeWithDefaultValue(Map $a) : void
{
assertType('int|string|null', $a->remove(1, null));
}

public function mapMerge() : void
{
$a = new Map([1 => new A()]);
Expand Down