Skip to content

Commit d071e71

Browse files
committed
Add support to create type with multiple string values
This is to help create phpstan types of string constants
1 parent b66bd81 commit d071e71

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/ValueObject/Type.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ final class Type
1919
private string $namespace = '';
2020
/** @var Type[] */
2121
private array $types = [];
22+
private bool $noneValidTypeHint = false;
2223

2324
/**
2425
* @param list<string> $types
@@ -38,6 +39,16 @@ public static function fromIdentifier(Identifier $identifier): self
3839
return self::fromString($identifier->toString());
3940
}
4041

42+
public static function enumString(string ...$values): self
43+
{
44+
$self = new self('');
45+
$self->noneValidTypeHint = true;
46+
foreach ($values as $value) {
47+
$self->types[] = new self("'$value'");
48+
}
49+
return $self;
50+
}
51+
4152
public static function fromString(string $type): self
4253
{
4354
if (!trim($type, '? ')) {
@@ -158,6 +169,10 @@ public function addUnion(Type|string $type): void
158169

159170
public function getTypeHint(bool $renderUnion = false): ?string
160171
{
172+
if ($this->noneValidTypeHint) {
173+
return null;
174+
}
175+
161176
if (count($this->types) > 1) {
162177
if ($renderUnion) {
163178
$typeHint = [];

tests/ValueObject/TypeTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,4 +326,31 @@ public function testMixedWithNullable(): void
326326
$this->assertSame('mixed|object', $type->getDocBlockTypeHint());
327327
$this->assertSame('mixed|object', $type->getTypeHint(true));
328328
}
329+
330+
public function testEnumStringValues(): void
331+
{
332+
$type = Type::enumString('value1', 'value2', 'value3');
333+
$this->assertSame("'value1'|'value2'|'value3'", $type->getDocBlockTypeHint());
334+
$this->assertNull($type->getTypeHint());
335+
$this->assertNull($type->getTypeHint(true));
336+
}
337+
338+
public function testEnumStringValueNullable(): void
339+
{
340+
$type = Type::enumString('value1', 'value2', 'value3');
341+
$type->addUnion('null');
342+
$this->assertSame("'value1'|'value2'|'value3'|null", $type->getDocBlockTypeHint());
343+
$this->assertNull($type->getTypeHint());
344+
$this->assertNull($type->getTypeHint(true));
345+
}
346+
347+
public function testEnumStringValueNullableAndClass(): void
348+
{
349+
$type = Type::enumString('value1', 'value2', 'value3');
350+
$type->addUnion('null');
351+
$type->addUnion(\BackedEnum::class);
352+
$this->assertSame("'value1'|'value2'|'value3'|BackedEnum|null", $type->getDocBlockTypeHint());
353+
$this->assertNull($type->getTypeHint());
354+
$this->assertNull($type->getTypeHint(true));
355+
}
329356
}

0 commit comments

Comments
 (0)