Skip to content

Commit

Permalink
fix bug when applying defaults for array items when the schema is for (
Browse files Browse the repository at this point in the history
…jsonrainbow#405)

all items and add support for minItems when applying defaults
  • Loading branch information
mathroc authored and erayd committed May 5, 2017
1 parent a9722e6 commit e231775
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/JsonSchema/Constraints/UndefinedConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,14 @@ protected function applyDefaultValues(&$value, $schema, $path)
}
}
} elseif (isset($schema->items) && LooseTypeCheck::isArray($value)) {
$items = array();
if (LooseTypeCheck::isArray($schema->items)) {
$items = $schema->items;
} elseif (isset($schema->minItems) && count($value) < $schema->minItems) {
$items = array_fill(count($value), $schema->minItems - count($value), $schema->items);
}
// $value is an array, and items are defined - treat as plain array
foreach ($schema->items as $currentItem => $itemDefinition) {
foreach ($items as $currentItem => $itemDefinition) {
if (
!array_key_exists($currentItem, $value)
&& property_exists($itemDefinition, 'default')
Expand Down
15 changes: 15 additions & 0 deletions tests/Constraints/DefaultPropertiesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,21 @@ public function getValidTests()
'{"items":[{"default":null}]}',
'[null]'
),
array(// #21 items might be a schema (instead of an array of schema)
'[{}]',
'{"items":{"properties":{"propertyOne":{"default":"valueOne"}}}}',
'[{"propertyOne":"valueOne"}]'
),
array(// #22 if items is not an array, it does not create a new item
'[]',
'{"items":{"properties":{"propertyOne":{"default":"valueOne"}}}}',
'[]'
),
array(// #23 if items is a schema with a default value and minItems is present, fill the array
'["a"]',
'{"items":{"default":"b"}, "minItems": 3}',
'["a","b","b"]'
),
);
}

Expand Down

0 comments on commit e231775

Please sign in to comment.