Skip to content

Added alternate way to instantiate validator #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -59,4 +73,4 @@ The following definitions are not yet supported:
- extends
- id
- $ref
- $schema
- $schema
18 changes: 12 additions & 6 deletions src/Json/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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?');
}
Expand Down