Skip to content

Commit 55a6482

Browse files
authored
Merge pull request #75 from bertramakers/str-enum
Add enum() method to Str class
2 parents e189816 + 11cdcdb commit 55a6482

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Schema/Field/Str.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ class Str extends Attribute
88
public ?int $maxLength = null;
99
public ?string $pattern = null;
1010
public ?string $format = null;
11+
public ?array $enum = null;
1112

1213
public function __construct(string $name)
1314
{
@@ -21,6 +22,11 @@ public function __construct(string $name)
2122
return;
2223
}
2324

25+
if ($this->enum !== null && !in_array($value, $this->enum, true)) {
26+
$enum = array_map(fn ($value) => '"' . $value . '"', $this->enum);
27+
$fail(sprintf('must be one of %s', implode(', ', $enum)));
28+
}
29+
2430
if (strlen($value) < $this->minLength) {
2531
$fail(sprintf('must be at least %d characters', $this->minLength));
2632
}
@@ -66,6 +72,13 @@ public function format(?string $format): static
6672
return $this;
6773
}
6874

75+
public function enum(?array $enum): static
76+
{
77+
$this->enum = $enum;
78+
79+
return $this;
80+
}
81+
6982
public function getSchema(): array
7083
{
7184
return parent::getSchema() + [
@@ -74,6 +87,7 @@ public function getSchema(): array
7487
'maxLength' => $this->maxLength,
7588
'pattern' => $this->pattern,
7689
'format' => $this->format,
90+
'enum' => $this->enum,
7791
];
7892
}
7993
}

tests/feature/StrTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,46 @@ public function test_validates_string()
5757
]),
5858
);
5959
}
60+
61+
public function test_invalid_enum()
62+
{
63+
$this->api->resource(
64+
new MockResource(
65+
'users',
66+
endpoints: [Create::make()],
67+
fields: [Str::make('type')->writable()->enum(['A', 'B'])],
68+
),
69+
);
70+
71+
$this->expectException(UnprocessableEntityException::class);
72+
73+
$this->api->handle(
74+
$this->buildRequest('POST', '/users')->withParsedBody([
75+
'data' => ['type' => 'users', 'attributes' => ['type' => 'C']],
76+
]),
77+
);
78+
}
79+
80+
public function test_valid_enum()
81+
{
82+
$this->api->resource(
83+
new MockResource(
84+
'users',
85+
endpoints: [Create::make()],
86+
fields: [Str::make('type')->writable()->enum(['A', 'B'])],
87+
),
88+
);
89+
90+
$response = $this->api->handle(
91+
$this->buildRequest('POST', '/users')->withParsedBody([
92+
'data' => ['type' => 'users', 'attributes' => ['type' => 'A']],
93+
]),
94+
);
95+
96+
$this->assertJsonApiDocumentSubset(
97+
['data' => ['attributes' => ['type' => 'A']]],
98+
$response->getBody(),
99+
true,
100+
);
101+
}
60102
}

0 commit comments

Comments
 (0)