Skip to content

Commit

Permalink
Merge pull request #9679 from robchett/mixedAssignment_from_template_var
Browse files Browse the repository at this point in the history
Don't throw UnnecesseryVarAnnotation when hinting a mixed template var
  • Loading branch information
orklah committed Apr 20, 2023
2 parents 0dcaf1c + 9083e0a commit b781bd9
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 4 deletions.
Expand Up @@ -191,7 +191,7 @@ public static function analyze(
&& $type_location
&& isset($context->vars_in_scope[$var_comment->var_id])
&& $context->vars_in_scope[$var_comment->var_id]->getId() === $comment_type->getId()
&& !$comment_type->isMixed()
&& !$comment_type->isMixed(true)
) {
$project_analyzer = $statements_analyzer->getProjectAnalyzer();

Expand Down
Expand Up @@ -270,7 +270,7 @@ public static function analyze(
&& $extended_var_id
&& (!$not_ignored_docblock_var_ids || isset($not_ignored_docblock_var_ids[$extended_var_id]))
&& $temp_assign_value_type->getId() === $comment_type->getId()
&& !$comment_type->isMixed()
&& !$comment_type->isMixed(true)
) {
if ($codebase->alter_code
&& isset($statements_analyzer->getProjectAnalyzer()->getIssuesToFix()['UnnecessaryVarAnnotation'])
Expand Down
17 changes: 15 additions & 2 deletions src/Psalm/Type/UnionTrait.php
Expand Up @@ -53,6 +53,8 @@
use function sort;
use function strpos;

use const ARRAY_FILTER_USE_BOTH;

/**
* @psalm-immutable
* @psalm-import-type TProperties from Union
Expand Down Expand Up @@ -796,9 +798,20 @@ public function hasMixed(): bool
/**
* @psalm-mutation-free
*/
public function isMixed(): bool
public function isMixed(bool $check_templates = false): bool
{
return isset($this->types['mixed']) && count($this->types) === 1;
return count(
array_filter(
$this->types,
static fn($type, $key): bool => $key === 'mixed'
|| $type instanceof TMixed
|| ($check_templates
&& $type instanceof TTemplateParam
&& $type->as->isMixed()
),
ARRAY_FILTER_USE_BOTH,
),
) === count($this->types);
}

/**
Expand Down
26 changes: 26 additions & 0 deletions tests/Template/ClassTemplateTest.php
Expand Up @@ -4112,6 +4112,32 @@ public function t(): string {
'$t===' => '\'\'',
],
],
'mixedAssignment' => [
'code' => '<?php
/** @template T */
abstract class Foo {
/** @psalm-var T */
protected $value;
/** @psalm-param T $value */
public function __construct($value)
{
/** @var T */
$value = $this->normalize($value);
$this->value = $value;
}
/**
* @psalm-param T $value
* @psalm-return T
*/
protected function normalize($value)
{
return $value;
}
}
',
],
];
}

Expand Down

0 comments on commit b781bd9

Please sign in to comment.