How to use Nette\Schema for getting structured default values?

medhi
Generous Backer | 255
+
0
-

Nette\Schema is awesome, but I would like to use it also for gathering default values. It works, I pass empty array as data to process and it returns default values set by ->default() parameter:

$defaults = $processor->process(Expect::structure([
				'text' => Expect::string()->default('My Text'),
				'justify' => Expect::anyOf(
					'start',
					'end',
					'center'
				)->default('start')
			]);, []);

BUT, it doesn't work, if elements are marked as required. It ends with error The mandatory item 'text' is missing.. It's logical, but how to proceed, when I just want to get structured default values, no matter if they are mandatory or not?

It would be nice to have something like $defaults = $processor->getDefaults().

David Grudl
Nette Core | 8206
+
0
-

Set structure as optional, Expect::structure(...)->required(false)

Felix
Nette Core | 1194
+
0
-

@medhi I was thinking about the same. PR was merged. Structure can be optional. :)

medhi
Generous Backer | 255
+
0
-

Thanks

medhi
Generous Backer | 255
+
0
-

David Grudl wrote:

Set structure as optional, Expect::structure(...)->required(false)

This still throws an exception (I forgot the ->setRequired(true) on the justify element in the original question):

$defaults = $processor->process(Expect::structure([
			'text' => Expect::string()->default('My text'),
			'justify' => Expect::anyOf(
				'start',
				'end',
				'center'
			)->default('start')->required(true)
		])->required(false), [])

When fetching default values, it should not matter, if they are required or not.

David Grudl
Nette Core | 8206
+
0
-

Hmm, it will probably be better to do it like Expect::anyOf([], Expect::structure([...]))

medhi
Generous Backer | 255
+
0
-

David Grudl wrote:

Hmm, it will probably be better to do it like Expect::anyOf([], Expect::structure([...]))

You mean like this?

$defaults = $processor->process(Expect::anyOf([], Expect::structure([
			'text' => Expect::string()->default('My text'),
			'justify' => Expect::anyOf(
				'start',
				'end',
				'center'
			)->default('start')->required(true)
		])->required(false)), []);

But it returns only empty array. My intention is to get an array of default values.

David Grudl
Nette Core | 8206
+
0
-

Sorry, I misread your post. There is no such function for gathering default value. Please create an issue.

medhi
Generous Backer | 255
+
0
-

David Grudl wrote:

Sorry, I misread your post. There is no such function for gathering default value. Please create an issue.

Issue created https://github.com/…ma/issues/39

Thanks