PHP code example of aklump / json-schema-validation

1. Go to this page and download the library: Download aklump/json-schema-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aklump / json-schema-validation example snippets


$path_to_schema = 'json_schema/foo.schema.json';
$schema_json = file_get_contents($path_to_schema);

// Create the validator for this schema.
$validate = new \AKlump\JsonSchema\ValidateWithSchema($schema_json, dirname($path_to_schema));

// Validate some data against the schema.
$errors = $validate(["lorem", "ipsum"]);

$is_valid = empty($errors);

// Display any errors.
if (!$is_valid) {
  foreach ($errors as $erro) {
    print $erro . PHP_EOL;
  }
}

$data = ['foo' => [1, 2, 3]];
$data_to_validate = (new \AKlump\JsonSchema\JsonDecodeLossless())(json_encode($data));
// $data_to_validate->foo[0] === 1

$schema_json = file_get_contents('greeting.schema.json');
$defaults = (new \AKlump\JsonSchema\GetPropertyDefaults())($schema_json);
// 'Hello, World!' === $defaults['greeting'];

/** @var array $dataset An empty dataset example */
$dataset = [];
$dataset = array_replace_recursive($defaults, $dataset);
// 'greeting' gets the default.
$dataset['greeting'] === 'Hello, World!';

/** @var array $dataset Greeting is already set. */
$dataset = ['greeting' => 'Yo, dude!']
$dataset = array_replace_recursive($defaults, $dataset);
// 'greeting keeps the non-default value.
$dataset['greeting'] === 'Yo, dude!';

/** @var array $dataset Greeting is an empty string, will not be replaced. */
$dataset = ['greeting' => '']
$dataset = array_replace_recursive($defaults, $dataset);
// 'greeting' is still an empty string.
$dataset['greeting'] === '';

$path_to_schema = 'json_schema/foo.schema.json';
ValidateWithSchema(file_get_contents($path_to_schema), dirname($path_to_schema);