Skip to content

Commit

Permalink
Fixed assigning to arrays with optional keys
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed May 10, 2020
1 parent a5beb06 commit 55c8a14
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Type/Constant/ConstantArrayTypeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PHPStan\Type\ArrayType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_filter;

class ConstantArrayTypeBuilder
{
Expand Down Expand Up @@ -74,6 +75,9 @@ public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $opt
foreach ($this->keyTypes as $i => $keyType) {
if ($keyType->getValue() === $offsetType->getValue()) {
$this->valueTypes[$i] = $valueType;
$this->optionalKeys = array_values(array_filter($this->optionalKeys, static function (int $index) use ($i): bool {
return $index !== $i;
}));
return;
}
}
Expand Down
9 changes: 9 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9894,6 +9894,14 @@ public function dataAssignNestedArray(): array
return $this->gatherAssertTypes(__DIR__ . '/data/assign-nested-arrays.php');
}

public function dataBug3276(): array
{
if (PHP_VERSION_ID < 70400) {
$this->markTestSkipped('Test requires PHP 7.4.');
}
return $this->gatherAssertTypes(__DIR__ . '/data/bug-3276.php');
}

/**
* @dataProvider dataBug2574
* @dataProvider dataBug2577
Expand Down Expand Up @@ -9941,6 +9949,7 @@ public function dataAssignNestedArray(): array
* @dataProvider dataBug3266
* @dataProvider dataBug3269
* @dataProvider dataAssignNestedArray
* @dataProvider dataBug3276
* @param ConstantStringType $expectedType
* @param Type $actualType
*/
Expand Down
28 changes: 28 additions & 0 deletions tests/PHPStan/Analyser/data/bug-3276.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php // lint >= 7.4

namespace Bug3276;

use function PHPStan\Analyser\assertType;

class Foo
{

/**
* @param array{name?:string} $settings
*/
public function doFoo(array $settings): void
{
$settings['name'] ??= 'unknown';
assertType('array(\'name\' => string)', $settings);
}

/**
* @param array{name?:string} $settings
*/
public function doBar(array $settings): void
{
$settings['name'] = 'unknown';
assertType('array(\'name\' => \'unknown\')', $settings);
}

}

0 comments on commit 55c8a14

Please sign in to comment.