From 337117df1dade22e2ba1fdc4a4b832c1e9b06b76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Barto=C5=A1?= Date: Thu, 31 Oct 2019 21:33:27 +0100 Subject: [PATCH] AnyOf: default value can be Schema (#12) --- src/Schema/Elements/AnyOf.php | 13 +++++++++++++ tests/Schema/Expect.anyOf.phpt | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/Schema/Elements/AnyOf.php b/src/Schema/Elements/AnyOf.php index 16543f0..ab75fbc 100644 --- a/src/Schema/Elements/AnyOf.php +++ b/src/Schema/Elements/AnyOf.php @@ -99,4 +99,17 @@ public function complete($value, Nette\Schema\Context $context) $context->addError("The option %path% expects to be $hints, " . static::formatValue($value) . ' given.'); } } + + + public function completeDefault(Context $context) + { + if ($this->required) { + $context->addError('The mandatory option %path% is missing.'); + return null; + } + if ($this->default instanceof Schema) { + return $this->default->completeDefault($context); + } + return $this->default; + } } diff --git a/tests/Schema/Expect.anyOf.phpt b/tests/Schema/Expect.anyOf.phpt index 243d4f7..24bb33b 100644 --- a/tests/Schema/Expect.anyOf.phpt +++ b/tests/Schema/Expect.anyOf.phpt @@ -161,3 +161,16 @@ test(function () { // processing Assert::same('two', $processor->processMultiple($schema, ['one', 'two'])); Assert::same(null, $processor->processMultiple($schema, ['one', null])); }); + + +test(function () { // Schema as default value + $default = Expect::structure([ + 'key2' => Expect::string(), + ])->castTo('array'); + + $schema = Expect::structure([ + 'key1' => Expect::anyOf(false, $default)->default($default), + ])->castTo('array'); + + Assert::same(['key1' => ['key2' => null]], (new Processor)->process($schema, null)); +});