File tree Expand file tree Collapse file tree 2 files changed +37
-22
lines changed
src/Psalm/Internal/Analyzer/Statements/Expression/Assignment Expand file tree Collapse file tree 2 files changed +37
-22
lines changed Original file line number Diff line number Diff line change @@ -349,29 +349,23 @@ private static function updateTypeWithKeyValues(
349
349
}
350
350
351
351
if (!$ has_matching_objectlike_property && !$ has_matching_string ) {
352
- if (count ($ key_values ) === 1 ) {
353
- $ key_value = $ key_values [0 ];
354
-
355
- $ object_like = new TKeyedArray (
356
- [$ key_value ->value => $ current_type ],
357
- $ key_value instanceof TLiteralClassString
358
- ? [$ key_value ->value => true ]
359
- : null ,
360
- );
361
-
362
- $ array_assignment_type = new Union ([
363
- $ object_like ,
364
- ]);
365
- } else {
366
- $ array_assignment_literals = $ key_values ;
367
-
368
- $ array_assignment_type = new Union ([
369
- new TNonEmptyArray ([
370
- new Union ($ array_assignment_literals ),
371
- $ current_type ,
372
- ]),
373
- ]);
352
+ $ properties = [];
353
+ $ classStrings = [];
354
+ $ current_type = $ current_type ->setPossiblyUndefined (count ($ key_values ) > 1 );
355
+ foreach ($ key_values as $ key_value ) {
356
+ $ properties [$ key_value ->value ] = $ current_type ;
357
+ if ($ key_value instanceof TLiteralClassString) {
358
+ $ classStrings [$ key_value ->value ] = true ;
359
+ }
374
360
}
361
+ $ object_like = new TKeyedArray (
362
+ $ properties ,
363
+ $ classStrings ?: null ,
364
+ );
365
+
366
+ $ array_assignment_type = new Union ([
367
+ $ object_like ,
368
+ ]);
375
369
376
370
return Type::combineUnionTypes (
377
371
$ child_stmt_type ,
Original file line number Diff line number Diff line change @@ -34,6 +34,27 @@ public function testConditionalAssignment(): void
34
34
public function providerValidCodeParse (): iterable
35
35
{
36
36
return [
37
+ 'assignUnionOfLiterals ' => [
38
+ 'code ' => '<?php
39
+ $result = [];
40
+
41
+ foreach (["a", "b"] as $k) {
42
+ $result[$k] = true;
43
+ }
44
+
45
+ $resultOpt = [];
46
+
47
+ foreach (["a", "b"] as $k) {
48
+ if (random_int(0, 1)) {
49
+ continue;
50
+ }
51
+ $resultOpt[$k] = true;
52
+ } ' ,
53
+ 'assertions ' => [
54
+ '$result=== ' => 'array{a: true, b: true} ' ,
55
+ '$resultOpt=== ' => 'array{a?: true, b?: true} ' ,
56
+ ],
57
+ ],
37
58
'genericArrayCreationWithSingleIntValue ' => [
38
59
'code ' => '<?php
39
60
$out = [];
You can’t perform that action at this time.
0 commit comments