Skip to content

Commit

Permalink
Merge pull request #8489 from hirokinoue/fix-array_key_exists-false-p…
Browse files Browse the repository at this point in the history
…ositive

Fix array_key_exists first argument false positive
  • Loading branch information
orklah committed Sep 18, 2022
2 parents 9ed9c4b + 9071e87 commit 3724a83
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3653,8 +3653,8 @@ private static function getArrayKeyExistsAssertions(
)
: null;

if ($array_root) {
if ($first_var_name === null && isset($expr->getArgs()[0])) {
if ($array_root && isset($expr->getArgs()[0])) {
if ($first_var_name === null) {
$first_arg = $expr->getArgs()[0];

if ($first_arg->value instanceof PhpParser\Node\Scalar\String_) {
Expand Down Expand Up @@ -3685,7 +3685,10 @@ private static function getArrayKeyExistsAssertions(
} else {
$first_var_name = null;
}
} elseif ($expr->getArgs()[0]->value instanceof PhpParser\Node\Expr\Variable
} elseif (($expr->getArgs()[0]->value instanceof PhpParser\Node\Expr\Variable
|| $expr->getArgs()[0]->value instanceof PhpParser\Node\Expr\PropertyFetch
|| $expr->getArgs()[0]->value instanceof PhpParser\Node\Expr\StaticPropertyFetch
)
&& $source instanceof StatementsAnalyzer
&& ($first_var_type = $source->node_data->getType($expr->getArgs()[0]->value))
) {
Expand Down
54 changes: 54 additions & 0 deletions tests/TypeReconciliation/ArrayKeyExistsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Psalm\Tests\TypeReconciliation;

use Psalm\Config;
use Psalm\Context;
use Psalm\Tests\TestCase;
use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;
Expand Down Expand Up @@ -430,4 +432,56 @@ function go(array $options): void {
],
];
}

public function testAllowPropertyFetchAsNeedle(): void
{
Config::getInstance()->ensure_array_int_offsets_exist = true;

$this->addFile(
'somefile.php',
'<?php
class Foo {
/** @var self::STATE_* $status */
public int $status = self::STATE_A;
public const STATE_A = 0;
public const STATE_B = 1;
}
$foo = new Foo;
/** @var array<string> $bar */
$bar = [];
if (array_key_exists($foo->status, $bar)) {
echo $bar[$foo->status];
}'
);

$this->analyzeFile('somefile.php', new Context());
}

public function testAllowStaticPropertyFetchAsNeedle(): void
{
Config::getInstance()->ensure_array_int_offsets_exist = true;

$this->addFile(
'somefile.php',
'<?php
class Foo {
/** @var self::STATE_* $status */
public static int $status = self::STATE_A;
public const STATE_A = 0;
public const STATE_B = 1;
}
/** @var array<string> $bar */
$bar = [];
if (array_key_exists(Foo::$status, $bar)) {
echo $bar[Foo::$status];
}'
);

$this->analyzeFile('somefile.php', new Context());
}
}

0 comments on commit 3724a83

Please sign in to comment.