Skip to content

Commit 378e0c0

Browse files
innocenzibrendt
authored andcommitted
feat(reflection): add union and intersection utils (#1798)
1 parent a996722 commit 378e0c0

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

packages/reflection/src/TypeReflector.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,16 @@ public function isNullable(): bool
215215
return $this->isNullable;
216216
}
217217

218+
public function isUnion(): bool
219+
{
220+
return str_contains($this->definition, '|');
221+
}
222+
223+
public function isIntersection(): bool
224+
{
225+
return str_contains($this->definition, '&');
226+
}
227+
218228
/** @return self[] */
219229
public function split(): array
220230
{

packages/reflection/tests/ReflectionTypeTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,24 @@ public function test_is_relation(): void
100100
$this->assertFalse(new TypeReflector(ImmutableString::class)->isRelation());
101101
$this->assertFalse(new TypeReflector(DateTimeImmutable::class)->isRelation());
102102
}
103+
104+
public function test_is_union(): void
105+
{
106+
$this->assertTrue(new TypeReflector('string|int')->isUnion());
107+
$this->assertTrue(new TypeReflector(A::class . '|' . B::class)->isUnion());
108+
$this->assertFalse(new TypeReflector('?string')->isUnion());
109+
$this->assertFalse(new TypeReflector('string')->isUnion());
110+
$this->assertFalse(new TypeReflector(A::class)->isUnion());
111+
$this->assertFalse(new TypeReflector('string&Stringable')->isUnion());
112+
}
113+
114+
public function test_is_intersection(): void
115+
{
116+
$this->assertTrue(new TypeReflector('string&Stringable')->isIntersection());
117+
$this->assertTrue(new TypeReflector(A::class . '&' . B::class)->isIntersection());
118+
$this->assertFalse(new TypeReflector('?string')->isIntersection());
119+
$this->assertFalse(new TypeReflector('string')->isIntersection());
120+
$this->assertFalse(new TypeReflector(A::class)->isIntersection());
121+
$this->assertFalse(new TypeReflector('string|int')->isIntersection());
122+
}
103123
}

0 commit comments

Comments
 (0)