Skip to content

Commit

Permalink
checkExplicitMixed - replace mixed type recursively
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Sep 8, 2021
1 parent 92ea742 commit b4f81db
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
14 changes: 11 additions & 3 deletions src/Rules/RuleLevelHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use PHPStan\Type\StrictMixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;

Expand Down Expand Up @@ -60,10 +61,17 @@ public function accepts(Type $acceptingType, Type $acceptedType, bool $strictTyp
{
if (
$this->checkExplicitMixed
&& $acceptedType instanceof MixedType
&& $acceptedType->isExplicitMixed()
) {
$acceptedType = new StrictMixedType();
$acceptedType = TypeTraverser::map($acceptedType, static function (Type $type, callable $traverse): Type {
if (
$type instanceof MixedType
&& $type->isExplicitMixed()
) {
return new StrictMixedType();
}

return $traverse($type);
});
}

if (
Expand Down
16 changes: 15 additions & 1 deletion tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@
class ReturnTypeRuleTest extends \PHPStan\Testing\RuleTestCase
{

/** @var bool */
private $checkExplicitMixed = false;

protected function getRule(): \PHPStan\Rules\Rule
{
return new ReturnTypeRule(new FunctionReturnTypeCheck(new RuleLevelHelper($this->createReflectionProvider(), true, false, true, false)));
return new ReturnTypeRule(new FunctionReturnTypeCheck(new RuleLevelHelper($this->createReflectionProvider(), true, false, true, $this->checkExplicitMixed)));
}

public function testReturnTypeRule(): void
Expand Down Expand Up @@ -527,4 +530,15 @@ public function testTemplateUnion(): void
]);
}

public function testBug5218(): void
{
$this->checkExplicitMixed = true;
$this->analyse([__DIR__ . '/data/bug-5218.php'], [
[
'Method Bug5218\IA::getIterator() should return Traversable<string, int> but returns ArrayIterator<string, mixed>.',
14,
],
]);
}

}
16 changes: 16 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-5218.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Bug5218;

/**
* @phpstan-implements \IteratorAggregate<string, int>
*/
final class IA implements \IteratorAggregate
{
/** @var array<string, mixed> */
private $data = [];

public function getIterator() : \Traversable {
return new \ArrayIterator($this->data);
}
}

0 comments on commit b4f81db

Please sign in to comment.