Skip to content

Commit e231775

Browse files
mathrocerayd
authored andcommitted
fix bug when applying defaults for array items when the schema is for (jsonrainbow#405)
all items and add support for minItems when applying defaults
1 parent a9722e6 commit e231775

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/JsonSchema/Constraints/UndefinedConstraint.php

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

tests/Constraints/DefaultPropertiesTest.php

+15
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)