Skip to content

Commit 331d41b

Browse files
mathrocbighappyface
authored andcommitted
fix bug when applying defaults for array items when the schema is for (#405)
all items and add support for minItems when applying defaults
1 parent 549b4af commit 331d41b

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
@@ -254,8 +254,14 @@ protected function applyDefaultValues(&$value, $schema, $path)
254254
}
255255
}
256256
} elseif (isset($schema->items) && LooseTypeCheck::isArray($value)) {
257+
$items = array();
258+
if (LooseTypeCheck::isArray($schema->items)) {
259+
$items = $schema->items;
260+
} elseif (isset($schema->minItems) && count($value) < $schema->minItems) {
261+
$items = array_fill(count($value), $schema->minItems - count($value), $schema->items);
262+
}
257263
// $value is an array, and items are defined - treat as plain array
258-
foreach ($schema->items as $currentItem => $itemDefinition) {
264+
foreach ($items as $currentItem => $itemDefinition) {
259265
if (
260266
!array_key_exists($currentItem, $value)
261267
&& 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)