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
all items and add support for minItems when applying defaults
  • Loading branch information
mathroc committed Mar 25, 2017
1 parent 2553ebd commit eef0954
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 @@ -253,8 +253,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 eef0954

Please sign in to comment.