diff --git a/src/JsonSchema/Constraints/BaseConstraint.php b/src/JsonSchema/Constraints/BaseConstraint.php index bc608f6d..b0fe8933 100644 --- a/src/JsonSchema/Constraints/BaseConstraint.php +++ b/src/JsonSchema/Constraints/BaseConstraint.php @@ -10,6 +10,7 @@ namespace JsonSchema\Constraints; use JsonSchema\ConstraintError; +use JsonSchema\Constraints\TypeCheck\LooseTypeCheck; use JsonSchema\Entity\JsonPointer; use JsonSchema\Exception\ValidationException; @@ -89,4 +90,22 @@ public function reset() { $this->errors = array(); } + + /** + * Recursively cast an associative array to an object + * + * @param array $array + * + * @return object + */ + public static function arrayToObjectRecursive($array) + { + foreach ($array as &$value) { + if (is_array($value)) { + $value = self::arrayToObjectRecursive($value); + } + } + + return LooseTypeCheck::isObject($array) ? (object) $array : $array; + } } diff --git a/src/JsonSchema/Validator.php b/src/JsonSchema/Validator.php index d479103c..0a9a8418 100644 --- a/src/JsonSchema/Validator.php +++ b/src/JsonSchema/Validator.php @@ -40,6 +40,11 @@ public function validate(&$value, $schema = null, $checkMode = null) // reset errors prior to validation $this->reset(); + // make sure $schema is an object + if (is_array($schema)) { + $schema = self::arrayToObjectRecursive($schema); + } + // set checkMode $initialCheckMode = $this->factory->getConfig(); if ($checkMode !== null) { diff --git a/tests/ValidatorTest.php b/tests/ValidatorTest.php new file mode 100644 index 00000000..a75ccecc --- /dev/null +++ b/tests/ValidatorTest.php @@ -0,0 +1,42 @@ +validate($data, $schema); + + $this->assertFalse($validator->isValid(), 'Validation succeeded, but should have failed.'); + } + + public function testCheck() + { + $schema = json_decode('{"type":"string"}'); + $data = json_decode('42'); + + $validator = new Validator(); + $validator->check($data, $schema); + + $this->assertFalse($validator->isValid(), 'Validation succeeded, but should have failed.'); + } + + public function testCoerce() + { + $schema = json_decode('{"type":"integer"}'); + $data = json_decode('"42"'); + + $validator = new Validator(); + $validator->coerce($data, $schema); + + $this->assertTrue($validator->isValid(), 'Validation failed, but should have succeeded.'); + } +}