diff --git a/src/Schema/Expect.php b/src/Schema/Expect.php index 69d9e30..eab3c84 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 080efd8..6d6c5f7 100644 --- a/tests/Schema/Expect.array.phpt +++ b/tests/Schema/Expect.array.phpt @@ -332,3 +332,18 @@ test('type[]', function () { Assert::same(['key' => 1], (new Processor)->process($schema, ['key' => 1])); }); + + +test('array shape', function () { + $schema = Expect::array([ + 'a' => Expect::string(), + 'b' => Expect::string('string'), + 'c' => Expect::anyOf(1, 2), + ]); + + Assert::type(Nette\Schema\Elements\Structure::class, $schema); + Assert::equal( + ['a' => null, 'b' => 'string', 'c' => null], + (new Processor)->process($schema, []), + ); +});