Skip to content

Commit

Permalink
Expect::array(shape) returns Structure
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Oct 5, 2024
1 parent 9522dad commit d10d6cd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Schema/Expect.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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);
Expand Down
14 changes: 14 additions & 0 deletions tests/Schema/Expect.array.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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, []),
);
});

0 comments on commit d10d6cd

Please sign in to comment.