Skip to content

Commit

Permalink
Specify existent offset with key variable when entering foreach
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Aug 22, 2022
1 parent 62ac4d9 commit 14592dd
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 7 deletions.
7 changes: 7 additions & 0 deletions src/Analyser/MutatingScope.php
Expand Up @@ -3143,6 +3143,13 @@ public function enterForeachKey(Expr $iteratee, string $keyName): self
$scope = $this->assignVariable($keyName, $iterateeType->getIterableKeyType());
$scope->nativeExpressionTypes[sprintf('$%s', $keyName)] = $nativeIterateeType->getIterableKeyType();

if ($iterateeType->isArray()->yes()) {
$scope = $scope->specifyExpressionType(
new Expr\ArrayDimFetch($iteratee, new Variable($keyName)),
$iterateeType->getIterableValueType(),
);
}

return $scope;
}

Expand Down
Expand Up @@ -429,12 +429,7 @@ public function testBug7142(): void
public function testBug6000(): void
{
$this->checkExplicitMixed = true;
$this->analyse([__DIR__ . '/data/bug-6000.php'], [
[
'Offset \'classmap\' does not exist on array{psr-4?: array<string, array<string>|string>, classmap?: array<int, string>}.',
12,
],
]);
$this->analyse([__DIR__ . '/data/bug-6000.php'], []);
}

public function testBug5743(): void
Expand Down Expand Up @@ -508,4 +503,9 @@ public function testBug7763(): void
$this->analyse([__DIR__ . '/data/bug-7763.php'], []);
}

public function testSpecifyExistentOffsetWhenEnteringForeach(): void
{
$this->analyse([__DIR__ . '/data/specify-existent-offset-when-entering-foreach.php'], []);
}

}
@@ -0,0 +1,22 @@
<?php

namespace SpecifyExistentOffsetWhenEnteringForeach;

class Foo
{

public function doFoo(string $s): void
{
$hintsToFind = ['ext-' => 0, 'lib-' => 0, 'php' => 99, 'composer' => 99];
foreach ($hintsToFind as $hintPrefix => $hintCount) {
if (str_starts_with($s, $hintPrefix)) {
if ($hintCount === 0 || $hintCount >= 99) {
$hintsToFind[$hintPrefix]++;
} elseif ($hintCount === 1) {
unset($hintsToFind[$hintPrefix]);
}
}
}
}

}
8 changes: 7 additions & 1 deletion tests/PHPStan/Rules/Functions/ImplodeFunctionRuleTest.php
Expand Up @@ -50,7 +50,13 @@ public function testFile(): void

public function testBug6000(): void
{
$this->analyse([__DIR__ . '/../Arrays/data/bug-6000.php'], []);
$this->analyse([__DIR__ . '/../Arrays/data/bug-6000.php'], [
[
// shouldn't be happening...
'Parameter #2 $array of function implode expects array<string>, array<int|string, array<string>|string> given.',
12,
],
]);
}

}

0 comments on commit 14592dd

Please sign in to comment.