Skip to content

Commit da801d5

Browse files
committed
Expect::array(shape) returns Structure
1 parent f441aec commit da801d5

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/Schema/Expect.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
* @method static Type float($default = null)
2525
* @method static Type bool($default = null)
2626
* @method static Type null()
27-
* @method static Type array($default = [])
2827
* @method static Type list($default = [])
2928
* @method static Type mixed($default = null)
3029
* @method static Type email($default = null)
@@ -95,6 +94,17 @@ public static function from(object $object, array $items = []): Structure
9594
}
9695

9796

97+
/**
98+
* @param mixed[] $shape
99+
*/
100+
public static function array(?array $shape = []): Structure|Type
101+
{
102+
return Nette\Utils\Arrays::first($shape ?? []) instanceof Schema
103+
? (new Structure($shape))->castTo('array')
104+
: (new Type('array'))->default($shape);
105+
}
106+
107+
98108
public static function arrayOf(string|Schema $valueType, string|Schema|null $keyType = null): Type
99109
{
100110
return (new Type('array'))->items($valueType, $keyType);

tests/Schema/Expect.array.phpt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,3 +332,18 @@ test('type[]', function () {
332332

333333
Assert::same(['key' => 1], (new Processor)->process($schema, ['key' => 1]));
334334
});
335+
336+
337+
test('array shape', function () {
338+
$schema = Expect::array([
339+
'a' => Expect::string(),
340+
'b' => Expect::string('string'),
341+
'c' => Expect::anyOf(1, 2),
342+
]);
343+
344+
Assert::type(Nette\Schema\Elements\Structure::class, $schema);
345+
Assert::equal(
346+
['a' => null, 'b' => 'string', 'c' => null],
347+
(new Processor)->process($schema, []),
348+
);
349+
});

0 commit comments

Comments
 (0)