Skip to content

Commit

Permalink
Allow the schema to be an associative array
Browse files Browse the repository at this point in the history
Implements jsonrainbow#388.
  • Loading branch information
erayd committed Mar 16, 2017
1 parent 3dba977 commit b65e3ba
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/JsonSchema/Constraints/BaseConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,22 @@ public function reset()
{
$this->errors = array();
}

/**
* Recursively cast an 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 (object) $array;
}
}
3 changes: 3 additions & 0 deletions src/JsonSchema/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class Validator extends BaseConstraint
*/
public function validate(&$value, $schema = null, $checkMode = null)
{
if (is_array($schema)) {
$schema = self::arrayToObjectRecursive($schema);
}
$initialCheckMode = $this->factory->getConfig();
if ($checkMode !== null) {
$this->factory->setConfig($checkMode);
Expand Down
42 changes: 42 additions & 0 deletions tests/ValidatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace JsonSchema\Tests;

use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;

class ValidatorTest extends \PHPUnit_Framework_TestCase
{
public function testValidateWithAssocSchema()
{
$schema = json_decode('{"type":"string"}', true);
$data = json_decode('42', true);

$validator = new Validator();
$validator->validate($data, $schema, Constraint::CHECK_MODE_NORMAL);

$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, Constraint::CHECK_MODE_NORMAL);

$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.');
}
}

0 comments on commit b65e3ba

Please sign in to comment.