Skip to content

Commit eef0954

Browse files
committed
fix bug when applying defaults for array items when the schema is for
all items and add support for minItems when applying defaults
1 parent 2553ebd commit eef0954

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/JsonSchema/Constraints/UndefinedConstraint.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,14 @@ protected function applyDefaultValues(&$value, $schema, $path)
253253
}
254254
}
255255
} elseif (isset($schema->items) && LooseTypeCheck::isArray($value)) {
256+
$items = array();
257+
if (LooseTypeCheck::isArray($schema->items)) {
258+
$items = $schema->items;
259+
} elseif (isset($schema->minItems) && count($value) < $schema->minItems) {
260+
$items = array_fill(count($value), $schema->minItems - count($value), $schema->items);
261+
}
256262
// $value is an array, and items are defined - treat as plain array
257-
foreach ($schema->items as $currentItem => $itemDefinition) {
263+
foreach ($items as $currentItem => $itemDefinition) {
258264
if (
259265
!array_key_exists($currentItem, $value)
260266
&& property_exists($itemDefinition, 'default')

tests/Constraints/DefaultPropertiesTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,21 @@ public function getValidTests()
149149
'{"items":[{"default":null}]}',
150150
'[null]'
151151
),
152+
array(// #21 items might be a schema (instead of an array of schema)
153+
'[{}]',
154+
'{"items":{"properties":{"propertyOne":{"default":"valueOne"}}}}',
155+
'[{"propertyOne":"valueOne"}]'
156+
),
157+
array(// #22 if items is not an array, it does not create a new item
158+
'[]',
159+
'{"items":{"properties":{"propertyOne":{"default":"valueOne"}}}}',
160+
'[]'
161+
),
162+
array(// #23 if items is a schema with a default value and minItems is present, fill the array
163+
'["a"]',
164+
'{"items":{"default":"b"}, "minItems": 3}',
165+
'["a","b","b"]'
166+
),
152167
);
153168
}
154169

0 commit comments

Comments
 (0)