-
-
Notifications
You must be signed in to change notification settings - Fork 947
Complex array shape not working properly #6364
Copy link
Copy link
Closed
Labels
Description
Bug report
Complex array shape doesn't work with switch that uses different shapes
<?php declare(strict_types = 1);
/**
* @phpstan-var array<string,
* array{
* type: 'Type1',
* id: string,
* jobs: array<string, string>
* } | array{
* type: 'Type2',
* id: string,
* job?: string,
* extractor?: int
* } | array{
* type: 'Type3',
* id: string,
* jobs: array<string, int>
* } | array{
* type: 'Type4',
* id: string,
* job?: string
* }>
*/
$array = [
'id1' => [
'type' => 'Type1',
'id' => 'subid1',
'jobs' => [
'key' => 'value',
'key2' => 'value2',
],
],
'id2' => [
'type' => 'Type2',
'id' => 'subid2',
'job' => 'value',
],
'id3' => [
'type' => 'Type2',
'id' => 'subid2',
],
'id4' => [
'type' => 'Type3',
'id' => 'subid4',
'jobs' => [
'key1' => 1,
'key2' => 2,
],
],
'id5' => [
'type' => 'Type4',
'id' => 'subid5',
'job' => 'value',
],
'id6' => [
'type' => 'Type4',
'id' => 'subid6',
],
];
foreach ($array as $key => $data) {
switch ($data['type']) {
case 'Type1':
echo $data['id'];
print_r($data['jobs']);
break;
case 'Type3':
$jobs = [];
foreach ($data['jobs'] as $job => $extractor) {
echo $job;
echo $extractor;
}
break;
case 'Type2':
echo $data['id'];
echo $data['job'] ?? 'default';
echo $data['extractor'] ?? 0;
break;
case 'Type4':
echo $data['id'];
echo $data['job'] ?? 'default';
break;
default:
throw new \RuntimeException('unknown type: ' . $data['type']);
}
}https://phpstan.org/r/a80de5c7-cec9-4a55-a3cc-059dd6e5bf60
Expected output
Expected no errors
Reactions are currently unavailable