swaggest/json-schema
PHP library for JSON Schema (Draft 4/6/7): import schemas, validate JSON data, and define high-level PHP structures with schema-based rules. Supports $ref/definitions, formats, and detailed validation errors for robust data validation.
Begin by installing the package via Composer: composer require swaggest/json-schema. Start with validating raw JSON data against a schema defined inline or fetched from a URI—Schema::import($jsonOrUri) is your entry point. For basic usage, decode JSON to an object, pass it to $schema->in($data), and handle InvalidValue exceptions for validation failures. To quickly get started with class-based schemas, create a class extending ClassStructure and override setUpProperties() to define validation rules via fluent schema construction—e.g., $properties->id = Schema::integer();.
Use ClassStructure subclasses for domain models to gain validation, import/export, and meta support out of the box. Define static setUpProperties() to declare property schemas, types, required fields, and metadata (e.g., database mappings). Leverage Schema::export($object) and Schema::import($data) for bidirectional conversion between PHP objects and JSON. Use Composition for flattening joined DB results into single objects (e.g., UserInfo + Order). Support multiple serialization formats (e.g., snake_case, camelCase) via addPropertyMapping() and switch contexts using Context::$mapping. For reusable schema fragments, embed child schemas (e.g., properties->info = UserInfo::schema()->nested();) and access nested data via UserInfo::pick($object) after composition import.
Validation of dynamic (docblock-defined) properties happens on every property assignment, causing runtime overhead—enable only where needed. Native properties are validated only during import/export, so setting them directly won’t fail until serialization. Be cautious with oneOf/anyOf schemas: error messages are verbose and nested—inspect InvalidValue::inspect() to build client-friendly error trees. Meta subclasses must be added to the schema before schema cloning occurs—e.g., in setUpProperties(). Use Context::skipValidation = true to bypass validation during performance-critical bulk imports, but do so carefully. Remember to pass Context explicitly when using custom mapping namespaces (e.g., Order::FANCY_MAPPING). Finally, schema definitions are lazily cloned to prevent cross-contamination—safe to mutate shared schemas in setUpProperties() without side effects.
How can I help you explore Laravel packages today?