nette / schema

📐 Validating data structures against a given Schema.
https://doc.nette.org/schema
Other
905 stars 26 forks source link

Add extend() method to Structure class #66

Closed gauthierm closed 1 month ago

gauthierm commented 5 months ago

An extend() method would be nice for Structure so you could define a base schema and then define variants with additional fields. Right now you can kind of do this like:

$baseItems = [
  'foo' => Expect::string(),
  'bar' => Expect::string(),
];

$base = Expect::structure($baseItems);
$variant = Expect::structure([
  ...$baseItems,
  'baz' => Expect::string()
];

This has a downside in that you need to expose the array and pass around the array rather than passing around Structure objects. When composing schemas it would be really nice to have the following API:


$base = Expect::structure([
  'foo' => Expect::string(),
  'bar' => Expect::string(),
]);

// make a new structure with additional or overridden fields
$variant = $base->extend([
  'baz' => Expect::string(),
]);

This would be similar to a feature present in Zod https://zod.dev/?id=extend