From d1150422eeff4926a35c2bda1e60791eb4cce7d4 Mon Sep 17 00:00:00 2001 From: Max Loeb Date: Thu, 13 Oct 2016 23:14:54 -0700 Subject: [PATCH] handle coercion of multiple types --- .../Constraints/ObjectConstraint.php | 26 ++++++++++--------- tests/Constraints/CoerciveTest.php | 10 +++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/JsonSchema/Constraints/ObjectConstraint.php b/src/JsonSchema/Constraints/ObjectConstraint.php index b0008f8e..ebbf1e10 100644 --- a/src/JsonSchema/Constraints/ObjectConstraint.php +++ b/src/JsonSchema/Constraints/ObjectConstraint.php @@ -201,18 +201,20 @@ protected function toInteger($value) */ protected function coerce($value, $definition) { - $type = isset($definition->type)?$definition->type:null; - if($type){ - switch($type){ - case "boolean": - $value = $this->toBoolean($value); - break; - case "integer": - $value = $this->toInteger($value); - break; - case "number": - $value = $this->toNumber($value); - break; + $types = isset($definition->type)?$definition->type:null; + if($types){ + foreach((array)$types as $type) { + switch ($type) { + case "boolean": + $value = $this->toBoolean($value); + break; + case "integer": + $value = $this->toInteger($value); + break; + case "number": + $value = $this->toNumber($value); + break; + } } } return $value; diff --git a/tests/Constraints/CoerciveTest.php b/tests/Constraints/CoerciveTest.php index bfec165b..d6fcb90a 100644 --- a/tests/Constraints/CoerciveTest.php +++ b/tests/Constraints/CoerciveTest.php @@ -58,6 +58,10 @@ public function testValidCoerceCases($input, $schema, $errors = array()) $this->assertTrue(gettype($value->integer) == "integer"); $this->assertTrue(gettype($value->boolean) == "boolean"); + $this->assertTrue(gettype($value->multitype1) == "boolean"); + $this->assertTrue(gettype($value->multitype2) == "double"); + $this->assertTrue(gettype($value->multitype3) == "integer"); + $this->assertTrue($validator->isValid(), print_r($validator->getErrors(), true)); } @@ -112,6 +116,9 @@ public function getValidCoerceTests() "array":[], "null":null, "any": "string", + "multitype1": "false", + "multitype2": "1.2", + "multitype3": "7", "any1": 2.6, "any2": 4, "any3": false, @@ -130,6 +137,9 @@ public function getValidCoerceTests() "array":{"type":"array"}, "null":{"type":"null"}, "any": {"type":"any"}, + "multitype1": {"type":["boolean","integer","number"]}, + "multitype2": {"type":["boolean","integer","number"]}, + "multitype3": {"type":["boolean","integer","number"]}, "any1": {"type":"any"}, "any2": {"type":"any"}, "any3": {"type":"any"},