Skip to content
Closed
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
@@ -0,0 +1,46 @@
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddReturnDocblockForDimFetchArrayFromAssignsRector\Fixture;

final class UnionFromIfElseAssign
{
public function toArray(): array
{
$items = [];

if (mt_rand(0, 1)) {
$items = ['id' => 1];
} else {
$items = ['name' => 'test'];
}

return $items;
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddReturnDocblockForDimFetchArrayFromAssignsRector\Fixture;

final class UnionFromIfElseAssign
{
/**
* @return array<string, int>|array<string, string>
*/
public function toArray(): array
{
$items = [];

if (mt_rand(0, 1)) {
$items = ['id' => 1];
} else {
$items = ['name' => 'test'];
}

return $items;
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode;
use Rector\Rector\AbstractRector;
use Rector\TypeDeclarationDocblocks\NodeFinder\ReturnNodeFinder;
use Rector\TypeDeclarationDocblocks\TagNodeAnalyzer\UsefulArrayTagNodeAnalyzer;
Expand Down Expand Up @@ -166,8 +168,18 @@ public function refactor(Node $node): ?ClassMethod
return $node;
}

// @todo handle multiple type nodes
$this->phpDocTypeChanger->changeReturnTypeNode($node, $phpDocInfo, $genericUnionedTypeNodes[0]);
if ($genericUnionedTypeNodes === []) {
return null;
}

// sort for deterministic output across PHP versions
usort($genericUnionedTypeNodes, static fn (TypeNode $a, TypeNode $b): int => (string) $a <=> (string) $b);

$typeNode = count($genericUnionedTypeNodes) === 1
? $genericUnionedTypeNodes[0]
: new BracketsAwareUnionTypeNode($genericUnionedTypeNodes);

$this->phpDocTypeChanger->changeReturnTypeNode($node, $phpDocInfo, $typeNode);

return $node;
}
Expand Down
Loading