Skip to content

Commit

Permalink
Fix #5799 — improve expansion of templated types
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed May 23, 2021
1 parent 89f815f commit d1262b0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/Psalm/Internal/Type/TemplateInferredTypeReplacer.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public static function replace(
$is_mixed = true;
}

$new_types[$template_type_part->getKey()] = $template_type_part;
$new_types[] = $template_type_part;
}
}
} elseif ($atomic_type instanceof Atomic\TTemplateParamClass) {
Expand Down Expand Up @@ -153,7 +153,7 @@ public static function replace(

if ($class_template_type) {
$keys_to_unset[] = $key;
$new_types[$class_template_type->getKey()] = $class_template_type;
$new_types[] = $class_template_type;
}
} elseif ($atomic_type instanceof Atomic\TTemplateIndexedAccess) {
$keys_to_unset[] = $key;
Expand Down Expand Up @@ -194,10 +194,10 @@ public static function replace(
$is_mixed = true;
}

$new_types[$template_type_part->getKey()] = $template_type_part;
$new_types[] = $template_type_part;
}
} else {
$new_types[$key] = new Atomic\TMixed();
$new_types[] = new Atomic\TMixed();
}
} elseif ($atomic_type instanceof Atomic\TConditional
&& $codebase
Expand Down Expand Up @@ -347,7 +347,7 @@ public static function replace(
$keys_to_unset[] = $key;

foreach ($class_template_type->getAtomicTypes() as $class_template_atomic_type) {
$new_types[$class_template_atomic_type->getKey()] = $class_template_atomic_type;
$new_types[] = $class_template_atomic_type;
}
}
}
Expand All @@ -359,7 +359,12 @@ public static function replace(
throw new \UnexpectedValueException('This array should be full');
}

$union->replaceTypes($new_types);
$union->replaceTypes(
TypeCombiner::combine(
$new_types,
$codebase
)->getAtomicTypes()
);

return;
}
Expand Down
26 changes: 26 additions & 0 deletions tests/Template/ClassTemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3371,6 +3371,32 @@ function writesLikeAnArray(WeakMap $wm): void {
}
',
],
'combineTwoTemplatedArrays' => [
'<?php
/** @template T */
class Option
{
/** @param T $v */
public function __construct(private $v) {}
/**
* @template E
* @param E $else
* @return T|E
*/
public function getOrElse($else)
{
return rand(0, 1) === 1 ? $this->v : $else;
}
}
$opt = new Option([1, 3]);
$b = $opt->getOrElse([2, 4])[0];',
[
'$b===' => '1|2'
]
],
];
}

Expand Down

0 comments on commit d1262b0

Please sign in to comment.