Skip to content

Commit

Permalink
Improve public API
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Nov 16, 2024
1 parent 08b5d34 commit b28026b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ class Field implements ArrayAccess, IteratorAggregate, Countable, StructuredFiel
/** @var array<HandledRequestCache> */
private array $caches;

public function __construct(HandledRequestCache|Stringable|string ...$caches)
public function __construct(HandledRequestCache|Item|StructuredFieldProvider|Stringable|string ...$caches)
{
$this->caches = array_map(fn (HandledRequestCache|Stringable|string $value) => match (true) {
$this->caches = array_map(fn (StructuredFieldProvider|Item|Stringable|string $value) => match (true) {
$value instanceof HandledRequestCache => $value,
$value instanceof StructuredFieldProvider,
$value instanceof Item => HandledRequestCache::fromStructuredField($value),
default => HandledRequestCache::fromHttpValue($value),
}, $caches);
}
Expand Down Expand Up @@ -240,7 +242,7 @@ public function offsetSet(mixed $offset, mixed $value): void
/**
* Append a new handled request cache at the end of the field.
*/
public function push(HandledRequestCache|Stringable|string ...$values): self
public function push(HandledRequestCache|Item|StructuredFieldProvider|Stringable|string ...$values): self
{
return match ($values) {
[] => $this,
Expand Down
10 changes: 9 additions & 1 deletion src/HandledRequestCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,20 @@ public static function fromHttpValue(Stringable|string $value, ?int $statusCode
/**
* Returns an instance from a Structured Field Item and the optional response status code.
*/
public static function fromStructuredField(Item $item, ?int $statusCode = null): self
public static function fromStructuredField(StructuredFieldProvider|Item $item, ?int $statusCode = null): self
{
if (null !== $statusCode && ($statusCode < 100 || $statusCode > 599)) {
throw new Exception('The default forward status code must be a valid HTTP status code when present.');
}

if ($item instanceof StructuredFieldProvider) {
$className = $item::class;
$item = $item->toStructuredField();
if (!$item instanceof Item) {
throw new Exception('The structured field provider `'.$className.'` must return an '.Item::class.' data type.');
}
}

$validation = self::validator()->validate($item);
if ($validation->isFailed()) {
throw new Exception('The submitted item is an invalid handled request cache status', previous: $validation->errors->toException());
Expand Down

0 comments on commit b28026b

Please sign in to comment.