44
55use PhpParser \Node ;
66use PHPStan \Analyser \Scope ;
7- use PHPStan \DependencyInjection \AutowiredParameter ;
87use PHPStan \DependencyInjection \RegisteredRule ;
98use PHPStan \Rules \Rule ;
109use PHPStan \Rules \RuleErrorBuilder ;
11- use PHPStan \Type \MixedType ;
10+ use PHPStan \Rules \RuleLevelHelper ;
11+ use PHPStan \Type \ErrorType ;
12+ use PHPStan \Type \Type ;
1213use PHPStan \Type \VerbosityLevel ;
1314use function sprintf ;
1415
@@ -20,8 +21,7 @@ final class InvalidKeyInArrayItemRule implements Rule
2021{
2122
2223 public function __construct (
23- #[AutowiredParameter]
24- private bool $ reportMaybes ,
24+ private RuleLevelHelper $ ruleLevelHelper ,
2525 )
2626 {
2727 }
@@ -37,23 +37,28 @@ public function processNode(Node $node, Scope $scope): array
3737 return [];
3838 }
3939
40- $ dimensionType = $ scope ->getType ($ node ->key );
40+ $ dimensionType = $ this ->ruleLevelHelper ->findTypeToCheck (
41+ $ scope ,
42+ $ node ->key ,
43+ '' ,
44+ static fn (Type $ dimType ): bool => AllowedArrayKeysTypes::getType ()->isSuperTypeOf ($ dimType )->yes (),
45+ )->getType ();
46+ if ($ dimensionType instanceof ErrorType) {
47+ return [];
48+ }
49+
4150 $ isSuperType = AllowedArrayKeysTypes::getType ()->isSuperTypeOf ($ dimensionType );
42- if ($ isSuperType ->no ()) {
43- return [
44- RuleErrorBuilder::message (
45- sprintf ('Invalid array key type %s. ' , $ dimensionType ->describe (VerbosityLevel::typeOnly ())),
46- )->identifier ('array.invalidKey ' )->build (),
47- ];
48- } elseif ($ this ->reportMaybes && $ isSuperType ->maybe () && !$ dimensionType instanceof MixedType) {
49- return [
50- RuleErrorBuilder::message (
51- sprintf ('Possibly invalid array key type %s. ' , $ dimensionType ->describe (VerbosityLevel::typeOnly ())),
52- )->identifier ('array.invalidKey ' )->build (),
53- ];
51+ if ($ isSuperType ->yes ()) {
52+ return [];
5453 }
5554
56- return [];
55+ return [
56+ RuleErrorBuilder::message (sprintf (
57+ '%s array key type %s. ' ,
58+ $ isSuperType ->no () ? 'Invalid ' : 'Possibly invalid ' ,
59+ $ dimensionType ->describe (VerbosityLevel::typeOnly ())
60+ ))->identifier ('array.invalidKey ' )->build (),
61+ ];
5762 }
5863
5964}
0 commit comments