Skip to content

Commit

Permalink
Fix array dim fetches with treatPhpDocTypesAsCertain: false
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Nov 22, 2020
1 parent 43fca8d commit a9ec174
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -2039,6 +2039,17 @@ public function getNativeType(Expr $expr): Type
return $this->nativeExpressionTypes[$key];
}

if ($expr instanceof Expr\ArrayDimFetch && $expr->dim !== null) {
return $this->getNullsafeShortCircuitingType(
$expr->var,
$this->getTypeFromArrayDimFetch(
$expr,
$this->getNativeType($expr->dim),
$this->getNativeType($expr->var)
)
);
}

return $this->getType($expr);
}

Expand Down
6 changes: 6 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10347,6 +10347,11 @@ public function dataIncDecInConditions(): array
return $this->gatherAssertTypes(__DIR__ . '/data/inc-dec-in-conditions.php');
}

public function dataBug4099(): array
{
return $this->gatherAssertTypes(__DIR__ . '/data/bug-4099.php');
}

/**
* @param string $file
* @return array<string, mixed[]>
Expand Down Expand Up @@ -10529,6 +10534,7 @@ private function gatherAssertTypes(string $file): array
* @dataProvider dataComparisonOperators
* @dataProvider dataBug3880
* @dataProvider dataIncDecInConditions
* @dataProvider dataBug4099
* @param string $assertType
* @param string $file
* @param mixed ...$args
Expand Down
41 changes: 41 additions & 0 deletions tests/PHPStan/Analyser/data/bug-4099.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Bug4099;

use function PHPStan\Analyser\assertNativeType;
use function PHPStan\Analyser\assertType;

class Foo
{

/**
* @param array{key: array{inner: mixed}} $arr
*/
function arrayHint(array $arr): void
{
assertType('array(\'key\' => array(\'inner\' => mixed))', $arr);
assertNativeType('array', $arr);

if (!array_key_exists('key', $arr)) {
assertType('*NEVER*', $arr);
assertNativeType('array', $arr);
throw new \Exception('no key "key" found.');
}
assertType('array(\'key\' => array(\'inner\' => mixed))', $arr);
assertNativeType('array&hasOffset(\'key\')', $arr);
assertType('array(\'inner\' => mixed)', $arr['key']);
assertNativeType('mixed', $arr['key']);

if (!array_key_exists('inner', $arr['key'])) {
assertType('array(\'key\' => *NEVER*)', $arr);
//assertNativeType('array(\'key\' => mixed)', $arr);
assertType('*NEVER*', $arr['key']);
//assertNativeType('mixed', $arr['key']);
throw new \Exception('need key.inner');
}

assertType('array(\'key\' => array(\'inner\' => mixed))', $arr);
assertNativeType('array(\'key\' => array(\'inner\' => mixed))', $arr);
}

}

0 comments on commit a9ec174

Please sign in to comment.