PHP code example of everlution / json-schema

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

    

everlution / json-schema example snippets




namespace App\JsonSchema;

use Everlution\JsonSchema\AbstractJsonSchema;

class JwtTokensRequestJsonSchema extends AbstractJsonSchema
{
    public function toArray(): array
    {
        $data = [
            'title' => 'JWT Token Request',
            'description' => 'Get a new token',
            'type' => 'object',
            'properties' => [
                'key' => [
                    'type' => 'string',
                ],
                'secret' => [
                    'type' => 'string',
                ],
                // you can use helpers like this to reduce the amount of code to write and reduce mistakes
                // 'whateverString' => $this->getTypeString(?bool $nullable, ?int $minLength, ?int $maxLength, ?string $pattern, ?string $format)
            ],
        ];
        
        // on this level add "additionalProperties": false
        $this->addAdditionalPropertiesFalse($data);
        // same as above but recursively in every sub level
        $this->addAdditionalPropertiesFalseRecursive($data);
        
        // on this level add "

use App\JsonSchema\JwtTokensRequestJsonSchema;

$jsonSchema = new JwtTokensRequestJsonSchema();

$jsonSchemaString = $jsonSchema->generate();

use App\JsonSchema\JwtTokensRequestJsonSchema;
use Everlution\JsonSchema\Validator\DefaultValidator;
use Everlution\JsonSchema\Validator\ValidatorException;
use JsonSchema\Validator as JustinrainbowJsonSchema;

$jsonSchema = new JwtTokensRequestJsonSchema();

$validator = new DefaultValidator(new JustinrainbowJsonSchema());

$data = [
    'key' => '123132',
    'secret' => '123213',
];

try {
    // validate() throws an exception only when the data cannot be validated against the JSON Schema
    $validator->validate($jsonSchema, $data);
} catch (ValidatorException $e) {
    var_dump($e->getErrors());
}