From 0ec8123ee6cc41b4db6d66a69d08fb45bce6524b Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 17 Dec 2020 22:13:46 +0100 Subject: [PATCH] added Type::mergeDefaults() [Closes #13, Closes #24, Closes #28, Closes #31] --- readme.md | 2 +- src/Schema/Elements/Type.php | 14 +++++++++++++- tests/Schema/Expect.array.phpt | 17 +++++++++++++++++ tests/Schema/Expect.list.phpt | 11 +++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 4bc0ba3..160f276 100644 --- a/readme.md +++ b/readme.md @@ -195,7 +195,7 @@ $processor->process($schema, ['foo', true, null, 'bar']); // OK $processor->process($schema, [123]); // ERROR ``` -The default value is `null`. +The default value is `null`. If you specify an array as default value, it merges it with the data. This can be disabled using `mergeDefaults(false)`. Structures diff --git a/src/Schema/Elements/Type.php b/src/Schema/Elements/Type.php index 38337db..adf0815 100644 --- a/src/Schema/Elements/Type.php +++ b/src/Schema/Elements/Type.php @@ -33,6 +33,9 @@ final class Type implements Schema /** @var string|null */ private $pattern; + /** @var bool */ + private $merge = true; + public function __construct(string $type) { @@ -49,6 +52,13 @@ public function nullable(): self } + public function mergeDefaults(bool $state = true): self + { + $this->merge = $state; + return $this; + } + + public function dynamic(): self { $this->type = DynamicParameter::class . '|' . $this->type; @@ -170,7 +180,9 @@ public function complete($value, Context $context) } } - $value = Helpers::merge($value, $this->default); + if ($this->merge) { + $value = Helpers::merge($value, $this->default); + } return $this->doFinalize($value, $context); } } diff --git a/tests/Schema/Expect.array.phpt b/tests/Schema/Expect.array.phpt index 985d729..9008a39 100644 --- a/tests/Schema/Expect.array.phpt +++ b/tests/Schema/Expect.array.phpt @@ -35,6 +35,23 @@ test('without default value', function () { }); +test('not merging', function () { + $schema = Expect::array([ + 'key1' => 'val1', + 'key2' => 'val2', + 'val3', + 'arr' => ['item'], + ])->mergeDefaults(false); + + Assert::same([], (new Processor)->process($schema, [])); + + Assert::same( + [1, 2, 3], + (new Processor)->process($schema, [1, 2, 3]) + ); +}); + + test('merging', function () { $schema = Expect::array([ 'key1' => 'val1', diff --git a/tests/Schema/Expect.list.phpt b/tests/Schema/Expect.list.phpt index c7989e6..42eea04 100644 --- a/tests/Schema/Expect.list.phpt +++ b/tests/Schema/Expect.list.phpt @@ -37,6 +37,17 @@ test('without default value', function () { }); +test('not merging', function () { + $schema = Expect::list([1, 2, 3])->mergeDefaults(false); + + Assert::same([], (new Processor)->process($schema, [])); + + Assert::same(['a', 'b', 'c'], (new Processor)->process($schema, ['a', 'b', 'c'])); + + Assert::same([], (new Processor)->process($schema, null)); +}); + + test('merging', function () { $schema = Expect::list([1, 2, 3]);