From eef0954a24deaf5870b594c13841033912195491 Mon Sep 17 00:00:00 2001 From: Mathieu Rochette Date: Thu, 23 Mar 2017 11:35:27 +0100 Subject: [PATCH] fix bug when applying defaults for array items when the schema is for all items and add support for minItems when applying defaults --- .../Constraints/UndefinedConstraint.php | 8 +++++++- tests/Constraints/DefaultPropertiesTest.php | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/JsonSchema/Constraints/UndefinedConstraint.php b/src/JsonSchema/Constraints/UndefinedConstraint.php index ed7d113f..7a0af0af 100644 --- a/src/JsonSchema/Constraints/UndefinedConstraint.php +++ b/src/JsonSchema/Constraints/UndefinedConstraint.php @@ -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') diff --git a/tests/Constraints/DefaultPropertiesTest.php b/tests/Constraints/DefaultPropertiesTest.php index a3b9c4e2..bcf90b2c 100644 --- a/tests/Constraints/DefaultPropertiesTest.php +++ b/tests/Constraints/DefaultPropertiesTest.php @@ -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"]' + ), ); }