Skip to content

Commit

Permalink
added Type::mergeDefaults() [Closes #13, Closes #24, Closes #28, Closes
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Dec 18, 2020
1 parent ec86ce7 commit 0ec8123
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 2 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 13 additions & 1 deletion src/Schema/Elements/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ final class Type implements Schema
/** @var string|null */
private $pattern;

/** @var bool */
private $merge = true;


public function __construct(string $type)
{
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}
}
17 changes: 17 additions & 0 deletions tests/Schema/Expect.array.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
11 changes: 11 additions & 0 deletions tests/Schema/Expect.list.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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]);

Expand Down

0 comments on commit 0ec8123

Please sign in to comment.