Skip to content

Commit b65e3ba

Browse files
committed
Allow the schema to be an associative array
Implements jsonrainbow#388.
1 parent 3dba977 commit b65e3ba

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

src/JsonSchema/Constraints/BaseConstraint.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,22 @@ public function reset()
8989
{
9090
$this->errors = array();
9191
}
92+
93+
/**
94+
* Recursively cast an array to an object
95+
*
96+
* @param array $array
97+
*
98+
* @return object
99+
*/
100+
public static function arrayToObjectRecursive($array)
101+
{
102+
foreach ($array as &$value) {
103+
if (is_array($value)) {
104+
$value = self::arrayToObjectRecursive($value);
105+
}
106+
}
107+
108+
return (object) $array;
109+
}
92110
}

src/JsonSchema/Validator.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ class Validator extends BaseConstraint
3636
*/
3737
public function validate(&$value, $schema = null, $checkMode = null)
3838
{
39+
if (is_array($schema)) {
40+
$schema = self::arrayToObjectRecursive($schema);
41+
}
3942
$initialCheckMode = $this->factory->getConfig();
4043
if ($checkMode !== null) {
4144
$this->factory->setConfig($checkMode);

tests/ValidatorTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
namespace JsonSchema\Tests;
4+
5+
use JsonSchema\Constraints\Constraint;
6+
use JsonSchema\Validator;
7+
8+
class ValidatorTest extends \PHPUnit_Framework_TestCase
9+
{
10+
public function testValidateWithAssocSchema()
11+
{
12+
$schema = json_decode('{"type":"string"}', true);
13+
$data = json_decode('42', true);
14+
15+
$validator = new Validator();
16+
$validator->validate($data, $schema, Constraint::CHECK_MODE_NORMAL);
17+
18+
$this->assertFalse($validator->isValid(), 'Validation succeeded, but should have failed.');
19+
}
20+
21+
public function testCheck()
22+
{
23+
$schema = json_decode('{"type":"string"}');
24+
$data = json_decode('42');
25+
26+
$validator = new Validator();
27+
$validator->check($data, $schema, Constraint::CHECK_MODE_NORMAL);
28+
29+
$this->assertFalse($validator->isValid(), 'Validation succeeded, but should have failed.');
30+
}
31+
32+
public function testCoerce()
33+
{
34+
$schema = json_decode('{"type":"integer"}');
35+
$data = json_decode('"42"');
36+
37+
$validator = new Validator();
38+
$validator->coerce($data, $schema);
39+
40+
$this->assertTrue($validator->isValid(), 'Validation failed, but should have succeeded.');
41+
}
42+
}

0 commit comments

Comments
 (0)