From 881dbf86e1561203e14366c70bb5782fd48920c4 Mon Sep 17 00:00:00 2001 From: Matt Brown Date: Mon, 3 May 2021 12:40:14 -0400 Subject: [PATCH] Fix inference for empty arrays --- .../Type/Comparator/ArrayTypeComparator.php | 17 +++++++++++++---- src/Psalm/Type/Atomic/TKeyedArray.php | 11 +++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/Psalm/Internal/Type/Comparator/ArrayTypeComparator.php b/src/Psalm/Internal/Type/Comparator/ArrayTypeComparator.php index 0f1579c4f..572e2daee 100644 --- a/src/Psalm/Internal/Type/Comparator/ArrayTypeComparator.php +++ b/src/Psalm/Internal/Type/Comparator/ArrayTypeComparator.php @@ -33,11 +33,20 @@ class ArrayTypeComparator ) : bool { $all_types_contain = true; - $is_empty_array = $input_type_part->getId() === 'array'; + $is_empty_array = $input_type_part->equals( + new Type\Atomic\TArray([ + new Type\Union([new Type\Atomic\TEmpty()]), + new Type\Union([new Type\Atomic\TEmpty()]) + ]), + false + ); + if ($is_empty_array - && ($container_type_part instanceof Type\Atomic\TArray - || $container_type_part instanceof Type\Atomic\TKeyedArray) - && !$container_type_part instanceof Type\Atomic\TNonEmptyArray + && (($container_type_part instanceof Type\Atomic\TArray + && !$container_type_part instanceof Type\Atomic\TNonEmptyArray) + || ($container_type_part instanceof Type\Atomic\TKeyedArray + && !$container_type_part->isNonEmpty()) + ) ) { return true; } diff --git a/src/Psalm/Type/Atomic/TKeyedArray.php b/src/Psalm/Type/Atomic/TKeyedArray.php index 2b71e348d..ff49f9ddb 100644 --- a/src/Psalm/Type/Atomic/TKeyedArray.php +++ b/src/Psalm/Type/Atomic/TKeyedArray.php @@ -294,6 +294,17 @@ class TKeyedArray extends \Psalm\Type\Atomic return $array_type; } + public function isNonEmpty(): bool + { + foreach ($this->properties as $key => $property) { + if (!$property->possibly_undefined) { + return true; + } + } + + return false; + } + public function __clone() { foreach ($this->properties as &$property) {