Skip to content

Commit

Permalink
Fix vimeo#2165 - coerce null array offset to zero
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Sep 25, 2019
1 parent 2d621f1 commit 1a48be8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 13 deletions.
Expand Up @@ -273,8 +273,8 @@ public static function getArrayAccessTypeGivenOffset(
PhpParser\Node\Expr\ArrayDimFetch $stmt,
Type\Union $array_type,
Type\Union $offset_type,
$in_assignment,
$array_var_id,
bool $in_assignment,
?string $array_var_id,
Context $context,
PhpParser\Node\Expr $assign_value = null,
Type\Union $replacement_type = null
Expand Down Expand Up @@ -326,19 +326,29 @@ public static function getArrayAccessTypeGivenOffset(
// fall through
}

return Type::getMixed();
if ($in_assignment) {
$offset_type->removeType('null');
$offset_type->addType(new TLiteralInt(0));
}
}

if ($offset_type->isNullable() && !$offset_type->ignore_nullable_issues && !$context->inside_isset) {
if (IssueBuffer::accepts(
new PossiblyNullArrayOffset(
'Cannot access value on variable ' . $array_var_id
. ' using possibly null offset ' . $offset_type,
new CodeLocation($statements_analyzer->getSource(), $stmt->var)
),
$statements_analyzer->getSuppressedIssues()
)) {
// fall through
if ($offset_type->isNullable() && !$context->inside_isset) {
if (!$offset_type->ignore_nullable_issues) {
if (IssueBuffer::accepts(
new PossiblyNullArrayOffset(
'Cannot access value on variable ' . $array_var_id
. ' using possibly null offset ' . $offset_type,
new CodeLocation($statements_analyzer->getSource(), $stmt->var)
),
$statements_analyzer->getSuppressedIssues()
)) {
// fall through
}
}

if ($in_assignment) {
$offset_type->removeType('null');
$offset_type->addType(new TLiteralInt(0));
}
}

Expand Down
28 changes: 28 additions & 0 deletions tests/ArrayAssignmentTest.php
Expand Up @@ -1117,6 +1117,34 @@ function foo(): array {
return $array;
}',
],
'coerceNullKeyToZero' => [
'<?php
function int_or_null(): ?int {
return rand(0, 1) !== 0 ? 42 : null;
}
/**
* @return array<array-key, null>
*/
function foo(): array {
$array = [];
/** @psalm-suppress PossiblyNullArrayOffset */
$array[int_or_null()] = null;
return $array;
}'
],
'coerceNullKeyToZero' => [
'<?php
/**
* @return array<int, null>
*/
function foo(): array {
$array = [];
/** @psalm-suppress NullArrayOffset */
$array[null] = null;
return $array;
}'
],
];
}

Expand Down

0 comments on commit 1a48be8

Please sign in to comment.