cortexphp/json-schema

A fluent JSON Schema builder for PHP

Installs: 24 077

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/cortexphp/json-schema

0.6.0 2025-07-01 08:29 UTC

README

banner

Fluently build and validate JSON Schemas

Latest Version GitHub Actions Test Workflow Status GitHub License

What is JSON Schema?

Features

  • 🏗️ Fluent Builder API - Build JSON Schemas using an intuitive fluent interface
  • 📝 Multi-Version Support - Support for JSON Schema Draft-07, Draft 2019-09, and Draft 2020-12
  • Validation - Validate data against schemas with detailed error messages
  • 🤝 Conditional Schemas - Support for if/then/else, allOf, anyOf, and not conditions
  • 🔄 Reflection - Generate schemas from PHP Classes, Enums and Closures
  • 💪 Type Safety - Built with PHP 8.3+ features and strict typing
  • 🔍 Version-Aware Features - Automatic validation of version-specific features with helpful error messages

JSON Schema Version Support

This package supports multiple JSON Schema specification versions with automatic feature validation:

Supported Versions

  • Draft-07 (2018) - Default version for maximum compatibility
  • Draft 2019-09 - Adds advanced features like $defs, unevaluatedProperties, deprecated
  • Draft 2020-12 - Latest version with prefixItems, dynamic references, and format vocabularies

Requirements

  • PHP 8.3+

Installation

composer require cortexphp/json-schema

Quick Start

use Cortex\JsonSchema\Schema;
use Cortex\JsonSchema\Enums\SchemaFormat;

// Create a schema
$schema = Schema::object('user')
    ->description('User schema')
    ->properties(
        Schema::string('name')
            ->minLength(2)
            ->maxLength(100)
            ->required(),
        Schema::string('email')
            ->format(SchemaFormat::Email)
            ->required(),
        Schema::integer('age')
            ->minimum(18)
            ->maximum(150),
        Schema::boolean('active')
            ->default(true),
        Schema::object('settings')
            ->additionalProperties(false)
            ->properties(
                Schema::string('theme')
                    ->enum(['light', 'dark']),
            ),
    );

$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'age' => 30,
    'active' => true,
    'settings' => [
        'theme' => 'light',
    ],
];

if ($schema->isValid($data)) {
    echo "Valid!";
} else {
    try {
        $schema->validate($data);
    } catch (\Cortex\JsonSchema\Exceptions\SchemaException $e) {
        echo $e->getMessage();
    }
}

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

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

Documentation

📚 View Full Documentation →

Credits

License

The MIT License (MIT). Please see License File for more information.