1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-21 21:31:13 +01:00

Fix #1130 - improve handling of invalid array offsets

This commit is contained in:
Brown 2018-12-14 15:10:10 -05:00
parent d9a42cf33d
commit b7d4db892c
4 changed files with 39 additions and 8 deletions

View File

@ -386,12 +386,14 @@ class ArrayFetchAnalyzer
$type->type_params[0] = $offset_type;
}
} elseif (!$type->type_params[0]->isEmpty()) {
$expected_offset_type = $type->type_params[0]->hasMixed()
? new Type\Union([ new TInt, new TString ])
: $type->type_params[0];
if ((!TypeAnalyzer::isContainedBy(
$codebase,
$offset_type,
$type->type_params[0]->hasMixed()
? new Type\Union([ new TInt, new TString ])
: $type->type_params[0],
$expected_offset_type,
true,
$offset_type->ignore_falsable_issues,
$has_scalar_match,
@ -402,7 +404,15 @@ class ArrayFetchAnalyzer
) && !$type_coerced_from_scalar)
|| $to_string_cast
) {
$expected_offset_types[] = $type->type_params[0]->getId();
if (TypeAnalyzer::canExpressionTypesBeIdentical(
$codebase,
$offset_type,
$expected_offset_type
)) {
$has_valid_offset = true;
}
$expected_offset_types[] = $expected_offset_type->getId();
} else {
$has_valid_offset = true;
}
@ -429,6 +439,7 @@ class ArrayFetchAnalyzer
}
if ($array_access_type->isEmpty()
&& !$array_type->hasMixed()
&& !$in_assignment
&& !$inside_isset
) {
@ -678,6 +689,7 @@ class ArrayFetchAnalyzer
}
}
$has_valid_offset = true;
$array_access_type = Type::getMixed();
break;
}

View File

@ -280,9 +280,7 @@ class TypeCombination
$array_type = new TArray($generic_type_params);
}
if (!$combination->has_mixed || !$generic_type_params[1]->isEmpty()) {
$new_types[] = $array_type;
}
$new_types[] = $array_type;
} elseif (!isset($combination->value_types[$generic_type])) {
$new_types[] = new TGenericObject($generic_type, $generic_type_params);
}

View File

@ -343,6 +343,27 @@ class ArrayAccessTest extends TestCase
["a" => $elt] = $entry;',
'error_message' => 'PossiblyUndefinedArrayOffset',
],
'possiblyInvalidMixedArrayOffset' => [
'<?php
/**
* @param string|array $key
*/
function foo(array $a, $key) : void {
echo $a[$key];
}',
'error_message' => 'PossiblyInvalidArrayOffset',
],
'possiblyInvalidMixedUnionArrayOffset' => [
'<?php
function foo(?array $index): void {
if (!$index) {
$index = ["foo", []];
}
$index[1][] = "bar";
}',
'error_message' => 'PossiblyInvalidArrayOffset',
'error_level' => ['MixedArrayAssignment'],
],
];
}
}

View File

@ -74,7 +74,7 @@ class TypeCombinationTest extends TestCase
],
],
'mixedOrEmptyArray' => [
'mixed',
'array<empty, empty>|mixed',
[
'mixed',
'array<empty, empty>',