From b28026bc0f8a2538e96fdfac3b0b6700eeeaba24 Mon Sep 17 00:00:00 2001 From: Ignace Nyamagana Butera Date: Sat, 16 Nov 2024 09:19:38 +0100 Subject: [PATCH] Improve public API --- src/Field.php | 8 +++++--- src/HandledRequestCache.php | 10 +++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/Field.php b/src/Field.php index b26edbd..9ca7457 100644 --- a/src/Field.php +++ b/src/Field.php @@ -33,10 +33,12 @@ class Field implements ArrayAccess, IteratorAggregate, Countable, StructuredFiel /** @var array */ 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); } @@ -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, diff --git a/src/HandledRequestCache.php b/src/HandledRequestCache.php index 01ef856..8c6c32d 100644 --- a/src/HandledRequestCache.php +++ b/src/HandledRequestCache.php @@ -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());