Skip to content

Commit

Permalink
AppendedArrayKeyTypeRule - more precise type description
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Aug 15, 2021
1 parent 6a33de9 commit aa9e2e8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Rules/Arrays/AppendedArrayKeyTypeRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,11 @@ public function processNode(\PhpParser\Node $node, Scope $scope): array
}

if (!$arrayType->getIterableKeyType()->isSuperTypeOf($keyType)->yes()) {
$verbosity = VerbosityLevel::getRecommendedLevelByType($arrayType->getIterableKeyType(), $keyType);
return [
RuleErrorBuilder::message(sprintf(
'Array (%s) does not accept key %s.',
$arrayType->describe(VerbosityLevel::typeOnly()),
$arrayType->describe($verbosity),
$keyType->describe(VerbosityLevel::value())
))->build(),
];
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Arrays/AppendedArrayKeyTypeRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ public function testRule(): void
'Array (array<string, mixed>) does not accept key 1.',
46,
],
[
'Array (array<1|2|3, string>) does not accept key int.',
80,
],
[
'Array (array<1|2|3, string>) does not accept key 4.',
85,
],
]);
}

Expand Down
18 changes: 18 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/appended-array-key.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,21 @@ public function doBar()
}

}

class MorePreciseKey
{

/** @var array<1|2|3, string> */
private $test;

public function doFoo(int $i): void
{
$this->test[$i] = 'foo';
}

public function doBar(): void
{
$this->test[4] = 'foo';
}

}

0 comments on commit aa9e2e8

Please sign in to comment.