PHP code example of v-ghost2000 / json-schema

1. Go to this page and download the library: Download v-ghost2000/json-schema 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/ */

    

v-ghost2000 / json-schema example snippets




class DateFilterObj implements IFilter
{
    /**
     * @inheritDoc
     */
    public function validate(&$date, array $args): bool
    {
        if (preg_match('#^(\d{1,2})\.(\d{1,2})\.(\d\d\d\d)$#', trim($date), $m)) {
            if (strlen($m[1]) === 1) {
                $m[1] = '0' . $m[1];
            }
            if (strlen($m[2]) === 1) {
                $m[2] = '0' . $m[2];
            }
            try {
                $date = DateTime::createFromFormat('Y-m-d', $m[3] . '-' . $m[2] . '-' . $m[1]);
                return true;
            } catch (Throwable $e) {}
        }

        return false;
    }
}



use Opis\JsonSchema\{
    Validator,
    FilterContainer,
    Schema
};

// Create a new FilterContainer
$filters = new FilterContainer();

// Register our modulo filter
$filters->add('string', 'dateFilter', new DateFilterObj);

// Create a IValidator
$validator = new Validator();

// Set filters to be used by validator
$validator->setFilters($filters);

$data = json_decode('{"date": "11.01.2020"}');
$schema = Schema::fromJsonString('
{
  "$schema":    "http://json-schema.org/draft-07/schema#",
  "$id":        "https://example.com/date.json",
  "type":       "object",
  "properties": {
    "date": {
      "type":   "string",
      "$filters": "dateFilter"
    }
  }
}
');


$result = $validator->schemaValidation($data, $schema);
if ($result->isValid()) {
    echo '$data is valid', PHP_EOL;
    echo $data->date->format('Y-m-d'), PHP_EOL; // 2020-01-11
} else {
    /** @var ValidationError $error */
    $error = $result->getFirstError();
    echo '$data is invalid', PHP_EOL;
    echo "Error: ", $error->keyword(), PHP_EOL;
    echo json_encode($error->keywordArgs(), JSON_PRETTY_PRINT), PHP_EOL;
}