Merge pull request #2646 from rectorphp/fix-var-const-unions

Fix Union Array type StaticTypeMapper to string
This commit is contained in:
Tomas Votruba 2020-01-12 00:53:26 +01:00 committed by GitHub
commit 5d71630ae6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 127 additions and 0 deletions

View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Tests\Rector\ClassConst\VarConstantCommentRector;
class UnionNestedAndSingleLevelArrayScalars
{
/**
* @var mixed[]
*/
public const ARRAY_CONST = [
'key2' => ['value2', 1234],
1 => null,
];
}
?>
-----
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Tests\Rector\ClassConst\VarConstantCommentRector;
class UnionNestedAndSingleLevelArrayScalars
{
/**
* @var int[][]|string[][]|null[]
*/
public const ARRAY_CONST = [
'key2' => ['value2', 1234],
1 => null,
];
}
?>

View File

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Tests\Rector\ClassConst\VarConstantCommentRector;
class UnionNestedArrayScalars
{
/**
* @var mixed[]
*/
public const STRING_ONLY = [
'key' => 'value',
];
/**
* @var mixed[]
*/
public const NESTED_STRING_INT = [
'key2' => ['value2', 1234],
];
/**
* @var mixed[]
*/
public const STRING_AND_NULL = [
'key' => 'value',
1 => null,
];
}
?>
-----
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Tests\Rector\ClassConst\VarConstantCommentRector;
class UnionNestedArrayScalars
{
/**
* @var string[]
*/
public const STRING_ONLY = [
'key' => 'value',
];
/**
* @var int[][]|string[][]
*/
public const NESTED_STRING_INT = [
'key2' => ['value2', 1234],
];
/**
* @var string[]|null[]
*/
public const STRING_AND_NULL = [
'key' => 'value',
1 => null,
];
}
?>

View File

@ -114,6 +114,11 @@ final class StaticTypeMapper
if ($phpStanType instanceof ArrayType || $phpStanType instanceof IterableType) {
$itemTypeNode = $this->mapPHPStanTypeToPHPStanPhpDocTypeNode($phpStanType->getItemType());
if ($itemTypeNode instanceof UnionTypeNode) {
return $this->convertUnionArrayTypeNodesToArrayTypeOfUnionTypeNodes($itemTypeNode);
}
return new ArrayTypeNode($itemTypeNode);
}
@ -868,4 +873,24 @@ final class StaticTypeMapper
return is_a($secondType->getClassName(), $firstType->getClassName(), true);
}
private function convertUnionArrayTypeNodesToArrayTypeOfUnionTypeNodes(
UnionTypeNode $unionTypeNode
): AttributeAwareUnionTypeNode {
$unionedArrayType = [];
foreach ($unionTypeNode->types as $unionedType) {
if ($unionedType instanceof UnionTypeNode) {
foreach ($unionedType->types as $key => $subUnionedType) {
$unionedType->types[$key] = new ArrayTypeNode($subUnionedType);
}
$unionedArrayType[] = $unionedType;
continue;
}
$unionedArrayType[] = new ArrayTypeNode($unionedType);
}
return new AttributeAwareUnionTypeNode($unionedArrayType);
}
}