Skip to content

Commit d572c0f

Browse files
committed
Add support for union type comparison
1 parent 3fe685a commit d572c0f

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/PHPSemVerChecker/Comparator/Type.php

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
namespace PHPSemVerChecker\Comparator;
55

66
use PhpParser\Node\NullableType;
7+
use PhpParser\Node\UnionType;
78

89
class Type
910
{
@@ -20,17 +21,27 @@ public static function isSame($typeA, $typeB): bool
2021
}
2122

2223
/**
23-
* @param \PhpParser\Node\Name|\PhpParser\Node\NullableType|string|null $type
24+
* @param \PhpParser\Node\Name|\PhpParser\Node\NullableType|\PhpParser\Node\UnionType|string|null $type
2425
* @return string|null
2526
*/
26-
public static function get($type)
27+
public static function get($type): ?string
2728
{
28-
if (! is_object($type)) {
29+
if ( ! is_object($type)) {
2930
return $type;
3031
}
3132

3233
if ($type instanceof NullableType) {
33-
return '?'.static::get($type->type);
34+
return '?' . static::get($type->type);
35+
}
36+
37+
if ($type instanceof UnionType) {
38+
$types = [];
39+
foreach ($type->types as $unionType) {
40+
$types[] = static::get($unionType);
41+
}
42+
// Sort to ensure consistent comparison even with different order of types
43+
sort($types);
44+
return implode('|', $types);
3445
}
3546

3647
return $type->toString();

tests/PHPSemVerChecker/Comparator/TypeComparatorTest.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
namespace PHPSemVerChecker\Test\Comparator;
44

5+
use PhpParser\Node\Identifier;
56
use PhpParser\Node\Name;
67
use PhpParser\Node\NullableType;
8+
use PhpParser\Node\UnionType;
79
use PHPSemVerChecker\Comparator\Type;
810
use PHPSemVerChecker\Test\TestCase;
911

@@ -22,7 +24,8 @@ public function isSameProvider()
2224
return [
2325
[Name::concat(null, 'test'), Name::concat(null, 'test')],
2426
['test', 'test'],
25-
[null, null]
27+
[null, null],
28+
[new UnionType([new Identifier('self'), new Identifier('array')]), new UnionType([new Identifier('array'), new Identifier('self')])],
2629
];
2730
}
2831

@@ -39,7 +42,8 @@ public function isNotSameProvider()
3942
return [
4043
[Name::concat(null, 'test'), Name::concat(null, 'test1')],
4144
['test', 'test1'],
42-
[null, 'test']
45+
[null, 'test'],
46+
[new UnionType([new Identifier('self'), new Identifier('array')]), null],
4347
];
4448
}
4549

@@ -59,6 +63,7 @@ public function getProvider()
5963
[Name::concat('namespaced', 'test'), 'namespaced\test'],
6064
[new NullableType('test'), '?test'],
6165
[new NullableType(Name::concat('namespaced', 'test')), '?namespaced\test'],
66+
[new UnionType([new Identifier('self'), new Identifier('array')]), 'array|self'],
6267
];
6368
}
6469
}

0 commit comments

Comments
 (0)