nette / schema

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

Possibility to use Schema to create an array/object of Schema's default values. #39

Open zraly opened 3 years ago

zraly commented 3 years ago

Intention

My intention is to use the Schema both to normalize the data and to obtain default values. In the second case, there is no need to input any data, just obtain an array of default values, if there are any.

My use case

I have several Personas, each of which can have very different parameters (saved as JSON in database).

The structure of these parameters is defined by the Persona's Schema.

I use the Persona's Schema to normalize these parameters entered by user's input.

To create a new Persona, however, I need to generate default values for its parameters from its Schema, so that I do not have to define them separately, because – why not use the existing Schema for this?

Example of my Schema for one of the Persona's:

Expect::structure([
    'nickname' => Expect::string()->default('Maniac'),
    'skills' => Expect::anyOf('low', 'medium', 'high')->default('low')->required(true)
]);

I need to use this Schema for normalization, which works great, but also to get the default values that are defined there. I need to get this result from this Schema:

[
   'nickname' => 'Maniac',
   'skills' => 'low'
]

When creating a new Persona, I encode this into JSON and save into database as default parameters of the Persona.

My idea is to have something like:

// normalized data
$normalized = $processor->process($schema, $data);

// default values
$defaults = $processor->getDefaults($schema);
// or
$defaults = $processor->process($schema);  // that is, no input data are specified, so it returns default values instead of normalized data