Skip to content

Commit

Permalink
report foreach on T of mixed
Browse files Browse the repository at this point in the history
  • Loading branch information
schlndh authored and ondrejmirtes committed Jan 21, 2024
1 parent a1d1293 commit 4321f19
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
62 changes: 61 additions & 1 deletion tests/PHPStan/Rules/Arrays/IterableInForeachRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Testing\RuleTestCase;
use function array_merge;
use function usort;
use const PHP_VERSION_ID;

/**
Expand All @@ -15,9 +17,11 @@ class IterableInForeachRuleTest extends RuleTestCase

private bool $checkExplicitMixed = false;

private bool $checkImplicitMixed = false;

protected function getRule(): Rule
{
return new IterableInForeachRule(new RuleLevelHelper($this->createReflectionProvider(), true, false, true, $this->checkExplicitMixed, false, true, false));
return new IterableInForeachRule(new RuleLevelHelper($this->createReflectionProvider(), true, false, true, $this->checkExplicitMixed, $this->checkImplicitMixed, true, false));
}

public function testCheckWithMaybes(): void
Expand Down Expand Up @@ -80,4 +84,60 @@ public function testBug4335(): void
$this->analyse([__DIR__ . '/data/bug-4335.php'], []);
}

public function dataMixed(): array
{
$explicitOnlyErrors = [
[
'Argument of an invalid type T of mixed supplied for foreach, only iterables are supported.',
11,
],
[
'Argument of an invalid type mixed supplied for foreach, only iterables are supported.',
14,
],
];
$implicitOnlyErrors = [
[
'Argument of an invalid type mixed supplied for foreach, only iterables are supported.',
17,
],
];
$combinedErrors = array_merge($explicitOnlyErrors, $implicitOnlyErrors);
usort($combinedErrors, static fn (array $a, array $b): int => $a[1] <=> $b[1]);

return [
[
true,
false,
$explicitOnlyErrors,
],
[
false,
true,
$implicitOnlyErrors,
],
[
true,
true,
$combinedErrors,
],
[
false,
false,
[],
],
];
}

/**
* @dataProvider dataMixed
* @param list<array{0: string, 1: int, 2?: string}> $errors
*/
public function testMixed(bool $checkExplicitMixed, bool $checkImplicitMixed, array $errors): void
{
$this->checkExplicitMixed = $checkExplicitMixed;
$this->checkImplicitMixed = $checkImplicitMixed;
$this->analyse([__DIR__ . '/data/foreach-mixed.php'], $errors);
}

}
19 changes: 19 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/foreach-mixed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php declare(strict_types=1); // lint >= 8.0

namespace ForeachMixed;

/**
* @template T
* @param T $t
*/
function foo(mixed $t, mixed $explicit, $implicit): void
{
foreach ($t as $v) {
}

foreach ($explicit as $v) {
}

foreach ($implicit as $v) {
}
}

0 comments on commit 4321f19

Please sign in to comment.