Skip to content

Commit 5e4d6ce

Browse files
committed
TASK: Union test that all members are deduplicated
1 parent 2a08474 commit 5e4d6ce

2 files changed

Lines changed: 39 additions & 4 deletions

File tree

src/TypeSystem/Type/UnionType/UnionType.php

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,15 @@
2525
use PackageFactory\ComponentEngine\TypeSystem\Type\NullType\NullType;
2626
use PackageFactory\ComponentEngine\TypeSystem\TypeInterface;
2727

28-
final class UnionType implements TypeInterface
28+
/**
29+
* @implements \IteratorAggregate<int, TypeInterface>
30+
*/
31+
final class UnionType implements TypeInterface, \IteratorAggregate, \Countable
2932
{
3033
/**
3134
* @var TypeInterface[]
3235
*/
33-
private array $members;
36+
private readonly array $members;
3437

3538
private function __construct(TypeInterface ...$members)
3639
{
@@ -57,7 +60,7 @@ public static function of(TypeInterface ...$members): TypeInterface
5760
return $uniqueMembers[0];
5861
}
5962

60-
return new self(...$members);
63+
return new self(...$uniqueMembers);
6164
}
6265

6366
public function isNullable(): bool
@@ -107,4 +110,15 @@ public function is(TypeInterface $other): bool
107110
return false;
108111
}
109112
}
113+
114+
/** @return \ArrayIterator<int, TypeInterface> */
115+
public function getIterator(): \ArrayIterator
116+
{
117+
return new \ArrayIterator($this->members);
118+
}
119+
120+
public function count(): int
121+
{
122+
return count($this->members);
123+
}
110124
}

test/Unit/TypeSystem/Type/UnionType/UnionTypeTest.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,27 @@ public function isReturnsTrueIfGivenTypeIsCongruentUnionTypeWithRedundantMembers
8787
$this->assertTrue($unionType->is($otherUnionType));
8888
}
8989

90+
/**
91+
* @test
92+
*/
93+
public function unionOnlyHoldsDeduplicatedMembers(): void
94+
{
95+
$unionType = UnionType::of(NumberType::get(), StringType::get());
96+
$otherUnionType = UnionType::of(NumberType::get(), StringType::get(), NumberType::get(), StringType::get());
97+
98+
$this->assertTrue($unionType->is($otherUnionType));
99+
100+
$this->assertInstanceOf(UnionType::class, $unionType);
101+
$this->assertInstanceOf(UnionType::class, $otherUnionType);
102+
103+
$this->assertCount(count($unionType), $otherUnionType);
104+
105+
$this->assertEqualsCanonicalizing(
106+
$unionType->getIterator()->getArrayCopy(),
107+
$otherUnionType->getIterator()->getArrayCopy()
108+
);
109+
}
110+
90111
/**
91112
* @test
92113
*/
@@ -97,4 +118,4 @@ public function isReturnsFalseIfGivenTypeIsNotCongruent(): void
97118
$this->assertFalse($unionType->is(NumberType::get()));
98119
$this->assertFalse($unionType->is(StringType::get()));
99120
}
100-
}
121+
}

0 commit comments

Comments
 (0)