PHP code example of cortexphp / json-schema

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

    

cortexphp / json-schema example snippets


use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaFormat;
use Cortex\JsonSchema\Enums\SchemaVersion;

// Create a basic user schema using the SchemaFactory
$schema = SchemaFactory::object('user')
    ->description('User schema')
    ->properties(
        SchemaFactory::string('name')
            ->minLength(2)
            ->maxLength(100)
            ->es(
                SchemaFactory::string('theme')
                    ->enum(['light', 'dark']),
            ),
    );

$schema = new ObjectSchema('user')
    ->description('User schema')
    ->properties(
        new StringSchema('name')
            ->minLength(2)
            ->maxLength(100)
            ->
        new BooleanSchema('active')
            ->default(true),
        new ObjectSchema('settings')
            ->additionalProperties(false)
            ->properties(
                new StringSchema('theme')->enum(['light', 'dark']),
            ),
    );

// Convert to array
$schema->toArray();

// Convert to JSON string
$schema->toJson();
$schema->toJson(JSON_PRETTY_PRINT);

$data = [
    'name' => 'John Doe',
    'email' => 'foo', // invalid email
    'age' => 16,
    'active' => true,
    'settings' => [
        'theme' => 'dark',
    ],
];

// Validate data against the schema
try {
    $schema->validate($data);
} catch (SchemaException $e) {
    echo $e->getMessage(); // "The data must match the 'email' format"
}

// Or just get a boolean
$schema->isValid($data); // false

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaVersion;

// Create schema with specific version
$schema = SchemaFactory::string('name', SchemaVersion::Draft_2020_12);

// Set global default version for all new schemas
SchemaFactory::setDefaultVersion(SchemaVersion::Draft_2019_09);

// Change version on existing schema
$schema->version(SchemaVersion::Draft_07);

// ✅ This works - deprecated is supported in Draft 2019-09+
$schema = SchemaFactory::string('oldField', SchemaVersion::Draft_2019_09)
    ->deprecated();

// ❌ This throws an exception - deprecated +
$arraySchema = SchemaFactory::array('items', SchemaVersion::Draft_2019_09)
    ->minContains(2)
    ->maxContains(5);

// ✅ Format validation for newer formats
$schema = SchemaFactory::string('duration', SchemaVersion::Draft_2019_09)
    ->format(SchemaFormat::Duration); // ISO 8601 duration format

// ✅ Unevaluated properties/items for advanced validation
$objectSchema = SchemaFactory::object('user', SchemaVersion::Draft_2019_09)
    ->properties(
        SchemaFactory::string('name')->

// Draft-07 uses 'definitions'
$draft07Schema = SchemaFactory::object('user', SchemaVersion::Draft_07)
    ->addDefinition('address', $addressSchema);
// Output: { "definitions": { "address": {...} } }

// Draft 2019-09+ uses '$defs'
$modernSchema = SchemaFactory::object('user', SchemaVersion::Draft_2019_09)
    ->addDefinition('address', $addressSchema);
// Output: { "$defs": { "address": {...} } }

use Cortex\JsonSchema\Enums\SchemaFeature;
use Cortex\JsonSchema\Enums\SchemaVersion;

// Check if a feature is supported
if (SchemaVersion::Draft_07->supports(SchemaFeature::Deprecated)) {
    // This will be false - deprecated is not supported in Draft 07
}

if (SchemaVersion::Draft_2019_09->supports(SchemaFeature::Deprecated)) {
    // This will be true - deprecated is supported in Draft 2019-09
}

// Get feature information
$feature = SchemaFeature::MinContains;
echo $feature->getDescription(); // "Minimum number of contains matches"
echo $feature->getMinimumVersion()->name; // "Draft201909"

// Create a schema using modern JSON Schema features
$modernSchema = SchemaFactory::object('user', SchemaVersion::Draft_2019_09)
    ->description('Modern user schema with advanced features')
    ->properties(
        SchemaFactory::string('username')
            ->minLength(3)
            ->        ->minContains(1) // Only available in Draft 2019-09+
            ->maxContains(10),
        SchemaFactory::string('uuid')
            ->format(SchemaFormat::Uuid) // Only available in Draft 2019-09+
    );

// This outputs a schema with "$defs" instead of "definitions"
// and 

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::string('name')
    ->minLength(2)
    ->maxLength(100)
    ->pattern('^[A-Za-z]+$')
    ->readOnly();

$schema->isValid('John Doe'); // true
$schema->isValid('John Doe123'); // false (contains numbers)
$schema->isValid('J'); // false (too short)

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::number('price')
    ->minimum(0)
    ->maximum(1000)
    ->multipleOf(0.01);

$schema->isValid(100); // true
$schema->isValid(1000.01); // false (too high)
$schema->isValid(0.01); // true
$schema->isValid(1.011); // false (not a multiple of 0.01)

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::integer('age')
    ->exclusiveMinimum(0)
    ->exclusiveMaximum(150)
    ->multipleOf(1);

$schema->isValid(18); // true
$schema->isValid(150); // false (too high)
$schema->isValid(0); // false (too low)
$schema->isValid(150.01); // false (not an integer)

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::boolean('active')
    ->default(true)
    ->readOnly();

$schema->isValid(true); // true
$schema->isValid(false); // true
$schema->isValid(null); // false

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::null('deleted_at');

$schema->isValid(null); // true
$schema->isValid(true); // false
$schema->isValid(false); // false

use Cortex\JsonSchema\SchemaFactory;

// Simple array of strings
$schema = SchemaFactory::array('tags')
    ->items(SchemaFactory::string())
    ->minItems(1)
    ->maxItems(3)
    ->uniqueItems(true);

$schema->isValid(['foo', 'bar']); // true
$schema->isValid(['foo', 'foo']); // false (not unique)
$schema->isValid([]); // false (too few items)
$schema->isValid(['foo', 'bar', 'baz', 'qux']); // false (too many items)

use Cortex\JsonSchema\SchemaFactory;

// Array must contain at least one number between 10 and 20
$schema = SchemaFactory::array('numbers')
    ->contains(
        SchemaFactory::number()
            ->minimum(10)
            ->maximum(20)
    )
    ->minContains(2) // must contain at least 2 such numbers
    ->maxContains(3); // must contain at most 3 such numbers

$schema->isValid([15, 12, 18]); // true (contains 3 numbers between 10-20)
$schema->isValid([15, 5, 25]); // false (only contains 1 number between 10-20)
$schema->isValid([15, 12, 18, 19]); // false (contains 4 numbers between 10-20)

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::array('coordinates')
    ->items(
        SchemaFactory::number()->description('latitude'),
        SchemaFactory::number()->description('longitude'),
    );

$schema->isValid([51.5074, -0.1278]); // true (valid lat/long)
$schema->isValid(['invalid', -0.1278]); // false (first item must be number)

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaFormat;

$schema = SchemaFactory::object('user')
    ->properties(
        SchemaFactory::string('name')->')->enum(['light', 'dark'])
        ),
    )
    ->additionalProperties(false);

$schema->isValid([
    'name' => 'John Doe',
    'email' => '[email protected]',
]); // true

$schema->isValid([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'settings' => [
        'theme' => 'dark',
    ],
]); // true

$schema->isValid([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'settings' => [
        'theme' => 'dark',
    ],
    'foo' => 'bar',
]); // false (additional properties)

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::object('config')
    // Validate property names against a pattern
    ->propertyNames(
        SchemaFactory::string()->pattern('^[a-zA-Z]+$')
    )
    // Control number of properties
    ->minProperties(1)
    ->maxProperties(10)
    // Control additional properties
    ->additionalProperties(false); // Disallow additional properties

// Or validate additional properties against a schema
$schema = SchemaFactory::object('config')
    ->properties(
        SchemaFactory::string('name')->

// Property names must be alphabetic
$schema->isValid(['123' => 'value']); // false
$schema->isValid(['validKey' => 'value']); // true

// Additional properties must match schema
$schema->isValid([
    'name' => 'config1',
    'type' => 'test',
    'extra' => 'valid', // valid: string with length >= 3
]); // true

$schema->isValid([
    'name' => 'config1',
    'type' => 'test',
    'extra' => 'no', // invalid: string too short
]); // false

$schema->isValid([
    'name' => 'config1',
    'type' => 'test',
    'extra' => 123, // invalid: wrong type
]); // false

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::object('config')
    // Add a single pattern property
    ->patternProperty('^prefix_',
        SchemaFactory::string()->minLength(5)
    )
    // Add multiple pattern properties
    ->patternProperties([
        '^[A-Z][a-z]+$' => SchemaFactory::string(), // CamelCase properties
        '^\d+$' => SchemaFactory::number(),         // Numeric properties
    ]);

// Valid data
$schema->isValid([
    'prefix_hello' => 'world123',  // Matches ^prefix_ and meets minLength
    'Name' => 'John',              // Matches ^[A-Z][a-z]+$
    '123' => 42,                   // Matches ^\d+$
]); // true

// Invalid data
$schema->isValid([
    'prefix_hi' => 'hi',           // Too short for minLength
    'invalid' => 'no pattern',     // Doesn't match any pattern
    '123' => 'not a number',       // Wrong type for pattern
]); // false

$schema = SchemaFactory::object('user')
    ->properties(
        SchemaFactory::string('name')->aFactory::string())
    ->additionalProperties(false);

// Valid:
$schema->isValid([
    'name' => 'John',
    'age' => 30,
    'custom_field' => 'value',  // Matches pattern
]);

// Invalid (property doesn't match pattern):
$schema->isValid([
    'name' => 'John',
    'age' => 30,
    'invalid_field' => 'value',
]);

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaVersion;

// Strict object validation - no unevaluated properties allowed
$schema = SchemaFactory::object('user', SchemaVersion::Draft_2019_09)
    ->properties(
        SchemaFactory::string('name')->('title')->(SchemaFactory::string())
    ->unevaluatedItems(false);

// Allow unevaluated items with schema validation
$arraySchema = SchemaFactory::array('mixed', SchemaVersion::Draft_2019_09)
    ->items(SchemaFactory::string())
    ->unevaluatedItems(
        SchemaFactory::integer()->minimum(0) // Extra items must be non-negative integers
    );

// unevaluatedProperties validation
$schema->isValid([
    'name' => 'John',
    'email' => '[email protected]',
]); // true

$schema->isValid([
    'name' => 'John',
    'email' => '[email protected]',
    'extra' => 'not allowed', // unevaluatedProperties: false
]); // false

// unevaluatedItems validation
$arraySchema->isValid(['hello', 'world']); // true (all items match string schema)
$arraySchema->isValid(['hello', 'world', 'extra']); // false (unevaluatedItems: false)

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaVersion;

// Simple dependent schema - when credit_card is present, billing_address is ory::string('credit_card'),
    )
    ->dependentSchema('credit_card',
        SchemaFactory::object()->properties(
            SchemaFactory::string('billing_address')->,
        SchemaFactory::boolean('is_premium'),
    )
    ->dependentSchemas([
        'payment_method' => SchemaFactory::object()
            ->if(SchemaFactory::object()->properties(
                SchemaFactory::string('payment_method')->const('credit_card')
            ))
            ->then(SchemaFactory::object()->properties(
                SchemaFactory::string('card_number')->

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaType;

$schema = SchemaFactory::union([SchemaType::String, SchemaType::Integer], 'id')
    ->description('ID can be either a string or an integer')
    ->enum(['abc123', 'def456', 1, 2, 3])
    ->nullable();

$schema->isValid('abc123'); // true
$schema->isValid(1); // true
$schema->isValid(null); // true (because it's nullable)
$schema->isValid(true); // false (not a string or integer)
$schema->isValid('invalid'); // false (not in enum)

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaFormat;

$schema = SchemaFactory::object('user')
    ->properties(
        SchemaFactory::string('email')->format(SchemaFormat::Email),
        SchemaFactory::string('website')->format(SchemaFormat::Uri),
        SchemaFactory::string('hostname')->format(SchemaFormat::Hostname),
        SchemaFactory::string('ipv4')->format(SchemaFormat::Ipv4),
        SchemaFactory::string('ipv6')->format(SchemaFormat::Ipv6),
        SchemaFactory::string('date')->format(SchemaFormat::Date),
        SchemaFactory::string('time')->format(SchemaFormat::Time),
        SchemaFactory::string('date_time')->format(SchemaFormat::DateTime),
        SchemaFactory::string('duration')->format(SchemaFormat::Duration),
        SchemaFactory::string('json_pointer')->format(SchemaFormat::JsonPointer),
        SchemaFactory::string('relative_json_pointer')->format(SchemaFormat::RelativeJsonPointer),
        SchemaFactory::string('uri_template')->format(SchemaFormat::UriTemplate),
        SchemaFactory::string('idn_email')->format(SchemaFormat::IdnEmail),
        SchemaFactory::string('idn_hostname')->format(SchemaFormat::Hostname),
        SchemaFactory::string('iri')->format(SchemaFormat::Iri),
        SchemaFactory::string('iri_reference')->format(SchemaFormat::IriReference),
    );

use Cortex\JsonSchema\SchemaFactory;

// if/then/else condition
$schema = SchemaFactory::object('user')
    ->properties(
        SchemaFactory::string('type')->enum(['personal', 'business']),
        SchemaFactory::string('company_name'),
        SchemaFactory::string('tax_id'),
    )
    ->if(
        SchemaFactory::object()->properties(
            SchemaFactory::string('type')->const('business'),
        ),
    )
    ->then(
        SchemaFactory::object()->properties(
            SchemaFactory::string('company_name')-> ->properties(
                SchemaFactory::integer('age')
                    ->minimum(18)
                    ->aFactory::object()
            ->properties(
                SchemaFactory::string('email')
                    ->format(SchemaFormat::Email)
                    ->

use Cortex\JsonSchema\SchemaFactory;

$schema = SchemaFactory::object('user')
    // Define a reusable address schema
    ->addDefinition(
        'address',
        SchemaFactory::object()
            ->properties(
                SchemaFactory::string('street')->
        SchemaFactory::object('billing_address')
            ->ref('#/definitions/address')
            ->

$schema = SchemaFactory::object('user')
    ->addDefinitions([
        'address' => SchemaFactory::object()
            ->properties(
                SchemaFactory::string('street')->('email')
                    ->format(SchemaFormat::Email)
                    ->

use Cortex\JsonSchema\Exceptions\SchemaException;

try {
    $schema->validate($data);
} catch (SchemaException $e) {
    echo $e->getMessage(); // "The data must match the 'email' format"
}

try {
    // This will throw an exception because 'deprecated' :Draft_07)
        ->deprecated();
} catch (SchemaException $e) {
    echo $e->getMessage();
    // "Feature 'Property deprecation annotation' is not supported in Draft 7.
    //  Minimum version ture 'Minimum number of contains matches' is not supported in Draft 7.
    //  Minimum version 

$schema
    ->title('Schema Title')
    ->description('Schema description')
    ->default('default value')
    ->examples(['example1', 'example2'])
    ->comment('Schema comment')
    ->readOnly()
    ->writeOnly();

use Cortex\JsonSchema\SchemaFactory;

/**
 * This is the description of the closure
 *
 * @param string $name The name of the user
 * @param array $meta The meta data of the user
 * @param ?int $age The age of the user
 */
$closure = function (string $name, array $meta, ?int $age = null): void {};

// Build the schema from the closure
$schema = SchemaFactory::fromClosure($closure);

// Convert to JSON Schema
$schema->toJson();

use Cortex\JsonSchema\SchemaFactory;

/**
 * This is the description of the class
 */
class User
{
    /**
     * @var string The name of the user
     */
    public string $name;

    /**
     * @var ?int The age of the user
     */
    public ?int $age = null;

    /**
     * @var float The height of the user in meters
     */
    public float $height = 1.7;
}

// Build the schema from the class with specific version
$schema = SchemaFactory::fromClass(User::class, version: SchemaVersion::Draft_2019_09);

// Convert to JSON Schema
$schema->toJson();

use Cortex\JsonSchema\SchemaFactory;

/**
 * This is the description of the enum
 */
enum PostType: int
{
    case Article = 1;
    case News = 2;
    case Tutorial = 3;
}

// Build the schema from the enum
$schema = SchemaFactory::fromEnum(PostType::class);

// Convert to JSON Schema
$schema->toJson();

use Cortex\JsonSchema\SchemaFactory;
use Cortex\JsonSchema\Enums\SchemaVersion;

// From a JSON string
$jsonString = '{
    "type": "object",
    "title": "User",
    "properties": {
        "name": {"type": "string", "minLength": 2},
        "email": {"type": "string", "format": "email"},
        "age": {"type": "integer", "minimum": 0}
    },
    "rk the same as any other schema
$schema->isValid('ABC-1234'); // true
$schema->isValid('invalid'); // false

// You can also modify the schema after creation
$schema->description('Product identification code')
    ->maxLength(8);

// Load from a file
$jsonSchema = file_get_contents('user-schema.json');
$schema = SchemaFactory::fromJson($jsonSchema);

// Validate some data
$userData = [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'age' => 30
];

if ($schema->isValid($userData)) {
    echo "User data is valid!";
}