1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-21 21:31:13 +01:00

Allow shortcut for specifying conditional template types

This commit is contained in:
Brown 2020-04-04 09:31:12 -04:00
parent 8f8cc6aed5
commit 56cc5fb611
2 changed files with 48 additions and 0 deletions

View File

@ -2462,6 +2462,37 @@ class ReflectorVisitor extends PhpParser\NodeVisitorAbstract implements PhpParse
$class_storage && !$class_storage->is_trait ? $class_storage->name : null
);
$param_type_mapping = [];
// This checks for param references in the return type tokens
// If found, the param is replaced with a generated template param
foreach ($fixed_type_tokens as $i => $type_token) {
if ($type_token[0][0] === '$') {
$token_body = $type_token[0];
foreach ($storage->params as $j => $param_storage) {
if ('$' . $param_storage->name === $token_body) {
if (!isset($param_type_mapping[$token_body])) {
$template_name = 'TGeneratedFromParam' . $j;
$storage->template_types[$template_name] = [
'fn-' . strtolower($cased_function_id) => [
$param_storage->type ? clone $param_storage->type : Type::getMixed()
],
];
$this->function_template_types[$template_name]
= $storage->template_types[$template_name];
$param_type_mapping[$token_body] = $template_name;
}
$fixed_type_tokens[$i][0] = $param_type_mapping[$token_body];
}
}
}
}
$storage->return_type = Type::parseTokens(
$fixed_type_tokens,
null,

View File

@ -190,6 +190,23 @@ class ConditionalReturnTypeTest extends TestCase
'$bool2' => 'bool',
]
],
'variableConditionalSyntax' => [
'<?php
/**
* @psalm-return ($i is 0 ? string : ($i is 1 ? int : bool))
*/
function getDifferentType(int $i) {
if ($i === 0) {
return "hello";
}
if ($i === 1) {
return 5;
}
return true;
}'
],
];
}
}