From 425d9fa8bfc43807d2715427692143b21e628496 Mon Sep 17 00:00:00 2001 From: Bruce Weirdan Date: Fri, 16 Dec 2022 20:12:02 -0400 Subject: [PATCH] Recognize casts from object-with-properties to array Previously `(array)(object)['a' => 1, 'b' => 'foo']` would result in `array`. Now it would be inferred as `array{a:1,b:foo,...}` --- .../Analyzer/Statements/Expression/CastAnalyzer.php | 9 +++++++++ tests/CastTest.php | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/CastAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/CastAnalyzer.php index a3e7ec685aa..c6b80ab5c9e 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/CastAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/CastAnalyzer.php @@ -259,6 +259,15 @@ public static function analyze( || $type instanceof TKeyedArray ) { $permissible_atomic_types[] = $type; + } elseif ($type instanceof TObjectWithProperties) { + $array_type = $type->properties === [] + ? new TArray([Type::getArrayKey(), Type::getMixed()]) + : new TKeyedArray( + $type->properties, + null, + [Type::getArrayKey(), Type::getMixed()] + ); + $permissible_atomic_types[] = $array_type; } else { $all_permissible = false; break; diff --git a/tests/CastTest.php b/tests/CastTest.php index 43397273ea1..fe93e5d7b3f 100644 --- a/tests/CastTest.php +++ b/tests/CastTest.php @@ -40,5 +40,14 @@ public function providerValidCodeParse(): iterable '$int===' => '0|1|int<10, 20>', ], ]; + yield 'castObjectWithPropertiesToArray' => [ + 'code' => ' [ + '$a===' => 'array{a: int, b: string, ...}', + ], + ]; } }