Skip to content

Commit f813495

Browse files
Do not report non existent offset when it s an array creation
1 parent 9dbff97 commit f813495

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

src/Rules/Arrays/NonexistentOffsetInArrayDimFetchRule.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
namespace PHPStan\Rules\Arrays;
44

55
use PhpParser\Node;
6+
use PhpParser\Node\Expr\ArrayDimFetch;
7+
use PhpParser\Node\Expr\Variable;
68
use PHPStan\Analyser\NullsafeOperatorHelper;
79
use PHPStan\Analyser\Scope;
810
use PHPStan\DependencyInjection\AutowiredParameter;
@@ -11,6 +13,7 @@
1113
use PHPStan\Rules\Rule;
1214
use PHPStan\Rules\RuleErrorBuilder;
1315
use PHPStan\Rules\RuleLevelHelper;
16+
use PHPStan\TrinaryLogic;
1417
use PHPStan\Type\ErrorType;
1518
use PHPStan\Type\Type;
1619
use PHPStan\Type\VerbosityLevel;
@@ -42,6 +45,10 @@ public function getNodeType(): string
4245

4346
public function processNode(Node $node, Scope $scope): array
4447
{
48+
if ($this->isImplicitArrayCreation($node, $scope)->yes()) {
49+
return [];
50+
}
51+
4552
if ($node->dim !== null) {
4653
$dimType = $scope->getType($node->dim);
4754
$unknownClassPattern = sprintf('Access to offset %s on an unknown class %%s.', SprintfHelper::escapeFormatString($dimType->describe(VerbosityLevel::value())));
@@ -153,4 +160,22 @@ public function processNode(Node $node, Scope $scope): array
153160
);
154161
}
155162

163+
private function isImplicitArrayCreation(Node\Expr\ArrayDimFetch $node, Scope $scope): TrinaryLogic
164+
{
165+
$varNode = $node->var;
166+
while ($varNode instanceof ArrayDimFetch) {
167+
$varNode = $varNode->var;
168+
}
169+
170+
if (!$varNode instanceof Variable) {
171+
return TrinaryLogic::createNo();
172+
}
173+
174+
if (!is_string($varNode->name)) {
175+
return TrinaryLogic::createNo();
176+
}
177+
178+
return $scope->hasVariableType($varNode->name)->negate();
179+
}
180+
156181
}

tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,19 @@ public function testBug3747(): void
926926
$this->analyse([__DIR__ . '/data/bug-3747.php'], []);
927927
}
928928

929+
public function testBug12447(): void
930+
{
931+
$this->checkExplicitMixed = true;
932+
$this->checkImplicitMixed = true;
933+
934+
$this->analyse([__DIR__ . '/data/bug-12447.php'], [
935+
[
936+
'Cannot access an offset on mixed.',
937+
5,
938+
],
939+
]);
940+
}
941+
929942
public function testBug8372(): void
930943
{
931944
$this->checkExplicitMixed = true;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug12447;
4+
5+
$data[] = 1;
6+
7+
function (): void {
8+
$data[] = 1;
9+
};

0 commit comments

Comments
 (0)