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 #388.
  • Loading branch information
erayd committed Mar 19, 2017
1 parent cf8e886 commit 465a947
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/JsonSchema/Constraints/BaseConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace JsonSchema\Constraints;

use JsonSchema\ConstraintError;
use JsonSchema\Constraints\TypeCheck\LooseTypeCheck;
use JsonSchema\Entity\JsonPointer;
use JsonSchema\Exception\ValidationException;

Expand Down Expand Up @@ -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;
}
}
5 changes: 5 additions & 0 deletions src/JsonSchema/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
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('{"properties":{"propertyOne":{"type":"array","items":[{"type":"string"}]}}}', true);
$data = json_decode('{"propertyOne":[42]}', true);

$validator = new Validator();
$validator->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.');
}
}

0 comments on commit 465a947

Please sign in to comment.