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 20, 2020
1 parent 80847f6 commit 0bfe37c
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 @@ -167,7 +167,7 @@ The parameter can also be a schema, so we can write:
Expect::arrayOf(Expect::bool())
```

The default value is an empty array.
The default value is an empty array. If you specify default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)`.


Enumeration: anyOf()
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 0bfe37c

Please sign in to comment.