From 3380de16a2ea0fb30218a14b4e0b0cc6a322fc7b Mon Sep 17 00:00:00 2001 From: Matthew Brown Date: Tue, 8 May 2018 23:17:11 -0400 Subject: [PATCH] Fix #709 - detect intersection template matches a bit better --- src/Psalm/Type/Union.php | 18 +++++++++++++++++- tests/TemplateTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/Psalm/Type/Union.php b/src/Psalm/Type/Union.php index c58c2cddd..edcb4d351 100644 --- a/src/Psalm/Type/Union.php +++ b/src/Psalm/Type/Union.php @@ -601,10 +601,26 @@ class Union $generic_params[$key]->setFromDocblock(); } } else { + $matching_atomic_type = null; + + if ($input_type) { + foreach ($input_type->types as $input_key => $atomic_input_type) { + if ($input_key === $key) { + $matching_atomic_type = $atomic_input_type; + break; + } + + if (strpos($input_key, $key . '&') === 0) { + $matching_atomic_type = $atomic_input_type; + break; + } + } + } + $atomic_type->replaceTemplateTypesWithStandins( $template_types, $generic_params, - isset($input_type->types[$key]) ? $input_type->types[$key] : null + $matching_atomic_type ); } } diff --git a/tests/TemplateTest.php b/tests/TemplateTest.php index 08275ed7a..9082545ee 100644 --- a/tests/TemplateTest.php +++ b/tests/TemplateTest.php @@ -471,6 +471,35 @@ class TemplateTest extends TestCase ], 'error_levels' => ['MixedAssignment', 'MixedArgument'], ], + 'intersectionTemplatedTypes' => [ + ' */ + private $data; + + /** @psalm-param iterable $data */ + public function __construct(iterable $data) { + $this->data = $data; + } + } + + class Item {} + /** @psalm-param Collection $c */ + function takesCollectionOfItems(Collection $c): void {} + + /** @psalm-var iterable $data2 */ + $data2 = []; + takesCollectionOfItems(new Collection($data2)); + + /** @psalm-var iterable&Countable $data */ + $data = []; + takesCollectionOfItems(new Collection($data));', + ], ]; }