From 6674dc8799fe63e49cac2f05e79d129a7ba0b926 Mon Sep 17 00:00:00 2001 From: Benjamin Keen Date: Wed, 14 Jan 2015 19:24:26 -0800 Subject: [PATCH] Added alternate way to instantiate validator The current code requires you to pass a file path when constructing the Validator; however, sometimes you don't have the schema in a file (e.g. it's in a database). This offers a second way to instantiate it, by passing in the raw JSON schema, and specifying it as "json" instead of a file location. --- README.md | 28 +++++++++++++++++++++------- src/Json/Validator.php | 18 ++++++++++++------ 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 62f0fbd..a072118 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,27 @@ draft can be found at http://tools.ietf.org/html/draft-zyp-json-schema-03 ## Usage - $someJson = '{"foo":"bar"}'; - $jsonObject = json_decode($someJson); - - $validator = new JsonValidator('/path/to/yourschema.json'); - - $validator->validate($jsonObject); +The standard way to use the JSON Validator is by passing in the location on your server to the +JSON schema and validating against it, like so: +```php +$someJson = '{"foo":"bar"}'; +$jsonObject = json_decode($someJson); + +$validator = new Validator('/path/to/yourschema.json'); +$validator->validate($jsonObject); +``` + +Alternatively you can pass in the raw JSON schema directly to the constructor: + +```php +$myRawJsonSchema = "{...}"; +$someJson = '{"foo":"bar"}'; +$jsonObject = json_decode($someJson); + +$validator = new Validator($myRawJsonSchema, "json"); +$validator->validate($jsonObject); +``` ## Supported Types @@ -59,4 +73,4 @@ The following definitions are not yet supported: - extends - id - $ref -- $schema \ No newline at end of file +- $schema diff --git a/src/Json/Validator.php b/src/Json/Validator.php index 939694d..3722df0 100644 --- a/src/Json/Validator.php +++ b/src/Json/Validator.php @@ -25,16 +25,22 @@ class Validator /** * Initialize validation object * - * @param string $schemaFile + * @param string $schema + * @param string $content "file", if the first param passed is a file location; "json" if it's raw JSON content + * @throws SchemaException */ - public function __construct($schemaFile) + public function __construct($schema, $content = "file") { - if (!file_exists($schemaFile)) { - throw new SchemaException(sprintf('Schema file not found: [%s]', $schemaFile)); + if ($content === "file") { + if (!file_exists($schema)) { + throw new SchemaException(sprintf('Schema file not found: [%s]', $schema)); + } + $data = file_get_contents($schema); + } else if ($content === "json") { + $data = $schema; } - $data = file_get_contents($schemaFile); - $this->schema = json_decode($data); + $this->schema = json_decode($data); if ($this->schema === null) { throw new SchemaException('Unable to parse JSON data - syntax error?'); }