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 6, 2024
1 parent f441aec commit da801d5
Show file tree
Hide file tree
Showing 2 changed files with 26 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
15 changes: 15 additions & 0 deletions tests/Schema/Expect.array.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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, []),
);
});

0 comments on commit da801d5

Please sign in to comment.