Skip to content

Add enum() method to Str class #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Schema/Field/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class Str extends Attribute
public ?int $maxLength = null;
public ?string $pattern = null;
public ?string $format = null;
public ?array $enum = null;

public function __construct(string $name)
{
Expand All @@ -21,6 +22,11 @@ public function __construct(string $name)
return;
}

if ($this->enum !== null && !in_array($value, $this->enum, true)) {
$enum = array_map(fn ($value) => '"' . $value . '"', $this->enum);
$fail(sprintf('must be one of %s', implode(', ', $enum)));
}

if (strlen($value) < $this->minLength) {
$fail(sprintf('must be at least %d characters', $this->minLength));
}
Expand Down Expand Up @@ -66,6 +72,13 @@ public function format(?string $format): static
return $this;
}

public function enum(?array $enum): static
{
$this->enum = $enum;

return $this;
}

public function getSchema(): array
{
return parent::getSchema() + [
Expand All @@ -74,6 +87,7 @@ public function getSchema(): array
'maxLength' => $this->maxLength,
'pattern' => $this->pattern,
'format' => $this->format,
'enum' => $this->enum,
];
}
}
42 changes: 42 additions & 0 deletions tests/feature/StrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,46 @@ public function test_validates_string()
]),
);
}

public function test_invalid_enum()
{
$this->api->resource(
new MockResource(
'users',
endpoints: [Create::make()],
fields: [Str::make('type')->writable()->enum(['A', 'B'])],
),
);

$this->expectException(UnprocessableEntityException::class);

$this->api->handle(
$this->buildRequest('POST', '/users')->withParsedBody([
'data' => ['type' => 'users', 'attributes' => ['type' => 'C']],
]),
);
}

public function test_valid_enum()
{
$this->api->resource(
new MockResource(
'users',
endpoints: [Create::make()],
fields: [Str::make('type')->writable()->enum(['A', 'B'])],
),
);

$response = $this->api->handle(
$this->buildRequest('POST', '/users')->withParsedBody([
'data' => ['type' => 'users', 'attributes' => ['type' => 'A']],
]),
);

$this->assertJsonApiDocumentSubset(
['data' => ['attributes' => ['type' => 'A']]],
$response->getBody(),
true,
);
}
}