Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@

namespace Rector\TypeDeclaration\Rector\FunctionLike;

use Iterator;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PHPStan\Type\ArrayType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\IterableType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use Rector\Exception\ShouldNotHappenException;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\RectorDefinition\CodeSample;
Expand Down Expand Up @@ -230,7 +236,12 @@ private function isReturnTypeAlreadyAdded(Node $node, Type $returnType): bool
return false;
}

if ($this->print($node->returnType) === $this->print($returnNode)) {
if ($this->areNodesEqual($node->returnType, $returnNode)) {
return true;
}

// is array <=> iterable <=> Iterator co-type? → skip
if ($this->isArrayIterableIteratorCoType($node, $returnType)) {
return true;
}

Expand All @@ -244,4 +255,42 @@ private function isReturnTypeAlreadyAdded(Node $node, Type $returnType): bool

return false;
}

private function isStaticTypeIterable(Type $type): bool
{
if ($type instanceof ArrayType) {
return true;
}

if ($type instanceof IterableType) {
return true;
}

if ($type instanceof ObjectType) {
if ($type->getClassName() === Iterator::class) {
return true;
}
}

if ($type instanceof UnionType || $type instanceof IntersectionType) {
foreach ($type->getTypes() as $joinedType) {
if (! $this->isStaticTypeIterable($joinedType)) {
return false;
}
}

return true;
}

return false;
}

private function isArrayIterableIteratorCoType(Node $node, Type $returnType): bool
{
if (! $this->isNames($node->returnType, ['iterable', 'Iterator', 'array'])) {
return false;
}

return $this->isStaticTypeIterable($returnType);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Rector\TypeDeclaration\Tests\Rector\ClassMethod\ReturnTypeDeclarationRector\Fixture;

use Iterator;

class SkipIterableArrayIteratorCoType
{
public function run(): Iterator
{
yield 5;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ public function provideDataForTests(): Iterator
yield [__DIR__ . '/Fixture/dunglas/nullable_types.php.inc'];
// anonymous class
yield [__DIR__ . '/Fixture/a_new_class.php.inc'];

yield [__DIR__ . '/Fixture/skip_iterable_array_iterator_co_type.php.inc'];
}

protected function getRectorClass(): string
Expand Down