4 * This file is part of the JsonSchema package.
6 * For the full copyright and license information, please view the LICENSE
7 * file that was distributed with this source code.
12 use JsonSchema\Constraints\BaseConstraint;
13 use JsonSchema\Constraints\Constraint;
14 use JsonSchema\Exception\InvalidConfigException;
15 use JsonSchema\SchemaStorage;
18 * A JsonSchema Constraint
20 * @author Robert Schönthal <seroscho@googlemail.com>
21 * @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
25 class Validator extends BaseConstraint
27 const SCHEMA_MEDIA_TYPE = 'application/schema+json';
29 const ERROR_NONE = 0x00000000;
30 const ERROR_ALL = 0xFFFFFFFF;
31 const ERROR_DOCUMENT_VALIDATION = 0x00000001;
32 const ERROR_SCHEMA_VALIDATION = 0x00000002;
35 * Validates the given data against the schema and returns an object containing the results
36 * Both the php object and the schema are supposed to be a result of a json_decode call.
37 * The validation works as defined by the schema proposal in http://json-schema.org.
39 * Note that the first argument is passwd by reference, so you must pass in a variable.
43 public function validate(&$value, $schema = null, $checkMode = null)
45 // make sure $schema is an object
46 if (is_array($schema)) {
47 $schema = self::arrayToObjectRecursive($schema);
51 $initialCheckMode = $this->factory->getConfig();
52 if ($checkMode !== null) {
53 $this->factory->setConfig($checkMode);
56 // add provided schema to SchemaStorage with internal URI to allow internal $ref resolution
57 $this->factory->getSchemaStorage()->addSchema(SchemaStorage::INTERNAL_PROVIDED_SCHEMA_URI, $schema);
59 $validator = $this->factory->createInstanceFor('schema');
62 $this->factory->getSchemaStorage()->getSchema(SchemaStorage::INTERNAL_PROVIDED_SCHEMA_URI)
65 $this->factory->setConfig($initialCheckMode);
67 $this->addErrors(array_unique($validator->getErrors(), SORT_REGULAR));
69 return $validator->getErrorMask();
73 * Alias to validate(), to maintain backwards-compatibility with the previous API
75 public function check($value, $schema)
77 return $this->validate($value, $schema);
81 * Alias to validate(), to maintain backwards-compatibility with the previous API
83 public function coerce(&$value, $schema)
85 return $this->validate($value, $schema, Constraint::CHECK_MODE_COERCE_TYPES);