PHP code example of sgpinkus / jsonschema

1. Go to this page and download the library: Download sgpinkus/jsonschema 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/ */

    

sgpinkus / jsonschema example snippets



sonSchema\JsonSchema;
use JsonRef\JsonDocs;

$json = '{
  "users": [
    {
     "comment": "valid",
     "firstName": "John",
     "lastName": "Doe",
     "email": "[email protected]",
     "_id": 1
    },
    {
     "comment": "invalid",
     "firstName": "John",
     "lastName": "Doe",
     "email": "john.doe.nowhere.com",
     "_id": 2
    }
  ]
}';
$schema = '{
  "type": "object",
  "properties": {
    "firstName": { "type": "string", "minLength": 2 },
    "lastName": { "type": "string", "minLength": 2 },
    "email": { "type": "string", "format": "email" },
    "_id": { "type": "integer" }
  },
  "


sonRef\JsonDocs;
use JsonSchema\JsonSchema;

$json = '{
  "comment": "valid",
  "firstName": "John",
  "lastName": "Doe",
  "email": "[email protected]",
  "_id": 1
}';
$schema = '{
  "id": "file:///tmp/jsonschema/user",
  "type": "object",
  "definitions" : {
    "_id" : { "type": "integer", "minimum": 0, "exclusiveMinimum": true },
    "commonName" : { "type": "string", "minLength": 2 }
  },
  "properties": {
    "firstName": { "$ref": "#/definitions/commonName" },
    "lastName": { "$ref": "#/definitions/commonName" },
    "email": { "type": "string", "format": "email" },
    "_id": { "$ref": "#/definitions/_id" }
  },
  "


sonSchema\JsonSchema;
use JsonSchema\Constraint\Constraint;
use JsonSchema\Constraint\Exception\ConstraintParseException;
use JsonSchema\Constraint\ValidationError;

class ModuloConstraint extends Constraint
{
  private $modulo;

  private function __construct(int $modulo) {
    $this->modulo = $modulo;
  }

  public static function getName() {
    return 'modulo';
  }

  public function validate($doc, $context) {
    if(is_int($doc) && $doc % $this->modulo !== 0) {
      return new ValidationError($this, "$doc is not modulo {$this->modulo}", $context);
    }
    return true;
  }

  public static function build($context) {
    if(!is_int($context->modulo)) {
      throw new ConstraintParseException("The value of 'modulo' MUST be an integer.");
    }

    return new static($context->modulo);
  }
}

$doc = 7;
$schema = '{
  "type": "integer",
  "modulo": 2
}';
$schema = new JsonSchema($schema, ['ModuloConstraint']);
$valid = $schema->validate($doc);
if($valid === true)
  print "OK\n";
else
  print $valid;