1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-29 20:28:59 +01:00

Fix #167 - prevent Empty type in assignment

This commit is contained in:
Matthew Brown 2017-06-28 23:37:02 -04:00
parent 4a590000a6
commit 8fd671bdc4
5 changed files with 34 additions and 4 deletions

View File

@ -91,6 +91,7 @@
<xs:element name="DeprecatedProperty" type="IssueHandlerType" minOccurs="0" />
<xs:element name="DuplicateParam" type="IssueHandlerType" minOccurs="0" />
<xs:element name="DuplicateClass" type="IssueHandlerType" minOccurs="0" />
<xs:element name="EmptyArrayAccess" type="IssueHandlerType" minOccurs="0" />
<xs:element name="FailedTypeResolution" type="IssueHandlerType" minOccurs="0" />
<xs:element name="ForbiddenCode" type="IssueHandlerType" minOccurs="0" />
<xs:element name="ImplicitToStringCast" type="IssueHandlerType" minOccurs="0" />

View File

@ -546,7 +546,8 @@ class AssignmentChecker
($lhs_type_part instanceof TNamedObject &&
in_array(
strtolower($lhs_type_part->value),
['stdclass', 'simplexmlelement', 'dateinterval', 'domdocument', 'domnode'], true
['stdclass', 'simplexmlelement', 'dateinterval', 'domdocument', 'domnode'],
true
)
)
) {

View File

@ -12,6 +12,7 @@ use Psalm\Checker\TraitChecker;
use Psalm\CodeLocation;
use Psalm\Context;
use Psalm\Issue\DeprecatedProperty;
use Psalm\Issue\EmptyArrayAccess;
use Psalm\Issue\InaccessibleClassConstant;
use Psalm\Issue\InvalidArrayAccess;
use Psalm\Issue\InvalidArrayAssignment;
@ -1064,6 +1065,18 @@ class FetchChecker
}
} elseif ($type instanceof Type\Atomic\TArray && $value_index !== null) {
$stmt->inferredType = $type->type_params[$value_index];
if ($stmt->inferredType->isEmpty()) {
if (IssueBuffer::accepts(
new EmptyArrayAccess(
'Cannot access value on empty array variable ' . $var_id,
new CodeLocation($statements_checker->getSource(), $stmt)
),
$statements_checker->getSuppressedIssues()
)) {
return false;
}
$stmt->inferredType = Type::getMixed();
}
} elseif ($type instanceof Type\Atomic\ObjectLike) {
$object_like_keys = array_keys($type->properties);
if ($object_like_keys) {

View File

@ -0,0 +1,6 @@
<?php
namespace Psalm\Issue;
class EmptyArrayAccess extends CodeError
{
}

View File

@ -43,7 +43,7 @@ class ArrayAccessTest extends TestCase
if ($a["bat"]) {
return $a["bat"];
}
return "blah";
}',
],
@ -56,7 +56,7 @@ class ArrayAccessTest extends TestCase
if ($a[0]) {
return $a[0];
}
return "blah";
}',
],
@ -64,9 +64,18 @@ class ArrayAccessTest extends TestCase
'<?php
$a = rand(0, 1) ? [1, 2] : null;
echo $a[0];',
'assertions' => [],
'error_levels' => ['PossiblyNullArrayAccess'],
],
'ignorePossiblyNullArrayAccess' => [
'<?php
$arr = [];
$x = $arr[0];
if (isset($arr[0]) && $arr[0]) { }',
'assertions' => [
['mixed' => '$x'],
],
'error_levels' => ['EmptyArrayAccess', 'MixedAssignment'],
],
];
}