From c271b1245eb2fc1f231d75f8f019e7f2434f7b09 Mon Sep 17 00:00:00 2001 From: AndrolGenhald Date: Thu, 2 Jun 2022 13:59:00 -0500 Subject: [PATCH] Fix possibly empty array shape appearing non-empty (fixes #8048). --- .../ArrayMergeReturnTypeProvider.php | 9 +++++++++ src/Psalm/Type/Atomic/TKeyedArray.php | 6 ++++-- tests/TypeReconciliation/TypeAlgebraTest.php | 11 +++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/Psalm/Internal/Provider/ReturnTypeProvider/ArrayMergeReturnTypeProvider.php b/src/Psalm/Internal/Provider/ReturnTypeProvider/ArrayMergeReturnTypeProvider.php index c4002a35f..c148fdd45 100644 --- a/src/Psalm/Internal/Provider/ReturnTypeProvider/ArrayMergeReturnTypeProvider.php +++ b/src/Psalm/Internal/Provider/ReturnTypeProvider/ArrayMergeReturnTypeProvider.php @@ -214,6 +214,15 @@ class ArrayMergeReturnTypeProvider implements FunctionReturnTypeProviderInterfac $inner_value_type = null; if ($inner_key_types) { + /** + * @psalm-suppress InvalidScalarArgument + * $inner_key_types is incorrectly inferred to be array{ + * 0?: Psalm\Type\Atomic|Psalm\Type\Atomic\TInt, + * 1?: Psalm\Type\Atomic|Psalm\Type\Atomic\TInt, + * ... + * 11?: Psalm\Type\Atomic|Psalm\Type\Atomic\TInt, + * } + */ $inner_key_type = TypeCombiner::combine($inner_key_types, $codebase, true); } diff --git a/src/Psalm/Type/Atomic/TKeyedArray.php b/src/Psalm/Type/Atomic/TKeyedArray.php index 15b0de859..e3b7399e5 100644 --- a/src/Psalm/Type/Atomic/TKeyedArray.php +++ b/src/Psalm/Type/Atomic/TKeyedArray.php @@ -408,13 +408,15 @@ class TKeyedArray extends Atomic return $this->getKey(); } - public function getList(): TNonEmptyList + public function getList(): TList { if (!$this->is_list) { throw new UnexpectedValueException('Object-like array must be a list for conversion'); } - return new TNonEmptyList($this->getGenericValueType()); + return $this->isNonEmpty() + ? new TNonEmptyList($this->getGenericValueType()) + : new TList($this->getGenericValueType()); } /** diff --git a/tests/TypeReconciliation/TypeAlgebraTest.php b/tests/TypeReconciliation/TypeAlgebraTest.php index 7ee1c97d5..428c51361 100644 --- a/tests/TypeReconciliation/TypeAlgebraTest.php +++ b/tests/TypeReconciliation/TypeAlgebraTest.php @@ -1420,6 +1420,17 @@ class TypeAlgebraTest extends TestCase false, '8.1', ], + 'arrayShapeListCanBeEmpty' => [ + ' $_list */ + function foobar(array $_list): void {} + + $list = random_int(0, 1) ? [] : ["foobar"]; + + foobar($list); + ', + 'error_message' => 'InvalidArgument', + ], ]; } }