Skip to content

Commit

Permalink
Prevent ArrayAccess on object from being memoised
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Apr 12, 2020
1 parent c733d6d commit 547efcc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/Psalm/Type/Reconciler.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,8 @@ public static function reconcileKeyedTypes(

$did_type_exist = isset($existing_types[$key]);

$has_object_array_access = false;

$result_type = isset($existing_types[$key])
? clone $existing_types[$key]
: self::getValueForKey(
Expand All @@ -239,7 +241,8 @@ public static function reconcileKeyedTypes(
$has_isset,
$has_inverted_isset,
$has_empty,
$inside_loop
$inside_loop,
$has_object_array_access
);

if ($result_type && empty($result_type->getAtomicTypes())) {
Expand Down Expand Up @@ -316,7 +319,9 @@ public static function reconcileKeyedTypes(
$result_type->failed_reconciliation = true;
}

$existing_types[$key] = $result_type;
if (!$has_object_array_access) {
$existing_types[$key] = $result_type;
}
}

return $existing_types;
Expand Down Expand Up @@ -448,7 +453,8 @@ private static function getValueForKey(
bool $has_isset,
bool $has_inverted_isset,
bool $has_empty,
bool $inside_loop
bool $inside_loop,
bool &$has_object_array_access
) {
$key_parts = self::breakUpPathIntoParts($key);

Expand Down Expand Up @@ -546,6 +552,9 @@ private static function getValueForKey(
return Type::getMixed($inside_loop);
} elseif ($existing_key_type_part instanceof TString) {
$new_base_type_candidate = Type::getString();
} elseif ($existing_key_type_part instanceof Type\Atomic\TNamedObject) {
$has_object_array_access = true;
return null;
} elseif (!$existing_key_type_part instanceof Type\Atomic\ObjectLike) {
return Type::getMixed();
} elseif ($array_key[0] === '$' || ($array_key[0] !== '\'' && !\is_numeric($array_key[0]))) {
Expand Down
7 changes: 6 additions & 1 deletion tests/ArrayAccessTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,12 @@ public function offsetUnset($offset) : void
$array = new C([]);
$array["key"] = [];
/** @psalm-suppress PossiblyInvalidArrayAssignment */
$array["key"][] = "testing";',
$array["key"][] = "testing";
$c = isset($array["foo"]) ? $array["foo"] : null;',
[
'$c' => 'C|null|scalar',
]
],
'singleLetterOffset' => [
'<?php
Expand Down

0 comments on commit 547efcc

Please sign in to comment.