From 9962564311f4affebd63f9cab014ab69266306ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milan=20Felix=20=C5=A0ulc?= Date: Mon, 17 Aug 2020 20:29:48 +0200 Subject: [PATCH] Structure: allow to skip defaults per structure --- src/Schema/Elements/Structure.php | 12 +++++++++++- tests/Schema/Expect.structure.phpt | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Schema/Elements/Structure.php b/src/Schema/Elements/Structure.php index 209c9a5..66edbee 100644 --- a/src/Schema/Elements/Structure.php +++ b/src/Schema/Elements/Structure.php @@ -29,6 +29,9 @@ final class Structure implements Schema /** @var array{?int, ?int} */ private $range = [null, null]; + /** @var bool */ + private $skipDefaults = false; + /** * @param Schema[] $items @@ -72,6 +75,13 @@ public function otherItems($type = 'mixed'): self } + public function skipDefaults(bool $state = true): self + { + $this->skipDefaults = $state; + return $this; + } + + /********************* processing ****************d*g**/ @@ -170,7 +180,7 @@ public function complete($value, Context $context) $value[$itemKey] = $itemVal->complete($value[$itemKey], $context); } else { $default = $itemVal->completeDefault($context); // checks required item - if (!$context->skipDefaults) { + if (!$context->skipDefaults && !$this->skipDefaults) { $value[$itemKey] = $default; } } diff --git a/tests/Schema/Expect.structure.phpt b/tests/Schema/Expect.structure.phpt index 376db5c..a2c7cb1 100644 --- a/tests/Schema/Expect.structure.phpt +++ b/tests/Schema/Expect.structure.phpt @@ -479,3 +479,25 @@ test('deprecated other items', function () { Assert::equal((object) ['key' => null, 'other' => 'foo'], $processor->process($schema, ['other' => 'foo'])); Assert::same(["The item 'other' is deprecated."], $processor->getWarnings()); }); + + +test('processing without default values skipped on structure', function () { + $schema = Expect::structure([ + 'foo1' => Expect::structure([ + 'bar' => Expect::string()->default('baz'), + ])->skipDefaults()->castTo('array'), + 'foo2' => Expect::structure([ + 'bar' => Expect::string()->default('baz'), + ])->castTo('array'), + ])->castTo('array'); + + $processor = new Processor; + + Assert::equal( + [ + 'foo1' => [], + 'foo2' => ['bar' => 'baz'], + ], + $processor->process($schema, []) + ); +});