From d10d6cd21f3b19b337b760693ef09792dddd6c1b Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 5 Oct 2024 02:51:56 +0200 Subject: [PATCH] Expect::array(shape) returns Structure --- src/Schema/Expect.php | 12 +++++++++++- tests/Schema/Expect.array.phpt | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Schema/Expect.php b/src/Schema/Expect.php index e56ae82..4be9319 100644 --- a/src/Schema/Expect.php +++ b/src/Schema/Expect.php @@ -24,7 +24,6 @@ * @method static Type float($default = null) * @method static Type bool($default = null) * @method static Type null() - * @method static Type array($default = []) * @method static Type list($default = []) * @method static Type mixed($default = null) * @method static Type email($default = null) @@ -95,6 +94,17 @@ public static function from(object $object, array $items = []): Structure } + /** + * @param mixed[] $shape + */ + public static function array(?array $shape = []): Structure|Type + { + return Nette\Utils\Arrays::first($shape ?? []) instanceof Schema + ? (new Structure($shape))->castTo('array') + : (new Type('array'))->default($shape); + } + + public static function arrayOf(string|Schema $valueType, string|Schema|null $keyType = null): Type { return (new Type('array'))->items($valueType, $keyType); diff --git a/tests/Schema/Expect.array.phpt b/tests/Schema/Expect.array.phpt index ea62f2e..27de8e6 100644 --- a/tests/Schema/Expect.array.phpt +++ b/tests/Schema/Expect.array.phpt @@ -364,3 +364,17 @@ test('merge modes', function () { ]), ); }); + + +test('array shape', function () { + $schema = Expect::array([ + 'a' => Expect::string(), + 'b' => Expect::string('string'), + 'c' => Expect::anyOf(1, 2), + ]); + + Assert::equal( + ['a' => null, 'b' => 'string', 'c' => null], + (new Processor)->process($schema, []), + ); +});