Skip to content

Commit

Permalink
Structure: allow to skip defaults per structure
Browse files Browse the repository at this point in the history
  • Loading branch information
f3l1x authored and dg committed Jan 21, 2021
1 parent 89c661d commit 9962564
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Schema/Elements/Structure.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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**/


Expand Down Expand Up @@ -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;
}
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Schema/Expect.structure.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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, [])
);
});

0 comments on commit 9962564

Please sign in to comment.