Download the PHP package spiral/json-schema-generator without Composer
On this page you can find all versions of the php package spiral/json-schema-generator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download spiral/json-schema-generator
More information about spiral/json-schema-generator
Files in spiral/json-schema-generator
Package json-schema-generator
Short Description Provides the ability to generate JSON schemas from Data Transfer Object (DTO) classes
License MIT
Homepage https://github.com/spiral/json-schema-generator
Informations about the package json-schema-generator
JSON Schema Generator
Overview
The JSON Schema Generator is a PHP package that simplifies the generation of JSON schemas from Data Transfer Object (DTO) classes.
Main use case: Structured output definition for LLMs.
Table of Contents
- Requirements
- Installation
- Basic Usage
- Class Properties and Enums
- Array Type Annotations
- Polymorphic Arrays (anyOf)
- Union Types
- Constraint Attributes
- PHPDoc Validation Constraints
- Format Support
- Additional Properties
- Configuration Options
- Integration with Valinor
- Testing
- Contributing
- License
Requirements
Make sure that your server is configured with the following PHP versions and extensions:
- PHP >=8.3
Installation
You can install the package via Composer:
Basic Usage
Let's create a simple DTO with an enum:
To generate a schema for a DTO, instantiate the Spiral\JsonSchemaGenerator\Generator
and call the generate method,
passing the DTO class as an argument (fully qualified class name or reflection). The method will return an instance of
Spiral\JsonSchemaGenerator\Schema
.
Note The package provides the
Spiral\JsonSchemaGenerator\GeneratorInterface,
which can be integrated into your application's dependency container for further customization and flexibility.
The generated schema for this DTO would include the following structure:
Array Type Annotations
The generator supports arrays of objects with type information from PHPDoc annotations:
Note Various documentation type annotations are supported:
@var array<Movie>
@var Movie[]
@var list<Movie>
For constructor-promoted properties, you can use annotations like:
@param array<Movie> $movies
@param Movie[] $movies
@param list<Movie> $movies
Generated schema (simplified):
Polymorphic Arrays (anyOf)
The generator supports arrays that contain different types of DTOs using PHPDoc annotations like
@var list<Movie|Series>
:
The generated schema will include an anyOf
definition in the items section:
Here's what the Series class might look like:
Note When using polymorphic arrays, make sure all referenced DTOs are properly annotated so their definitions can be generated correctly.
Union Types
The JSON Schema Generator supports native PHP union types (introduced in PHP 8.0), including nullable and multi-type definitions:
The generated schema will include a oneOf
section to reflect the union types:
Constraint Attributes
Generator supports dedicated constraint attributes that provide a clean, modular approach to validation rules.
Available Constraint Attributes
String Constraints
#[Pattern(regex)]
- Regular expression pattern validation#[Length(min, max)]
- String length constraints
Numeric Constraints
#[Range(min, max, exclusiveMin, exclusiveMax)]
- Numeric range validation with optional exclusive bounds#[MultipleOf(value)]
- Multiple of validation for numbers
Array Constraints
#[Items(min, max, unique)]
- Array item constraints with optional uniqueness#[Length(min, max)]
- Array length constraints (same attribute as strings, auto-detects type)
General Constraints
#[Enum(values)]
- Enumeration validation with array of allowed values
Usage Examples
String Validation
Numeric Validation
Array and Enum Validation
Generated Schema Output
The constraint attributes generate clean, standards-compliant JSON Schema validation rules:
Type Safety
Constraint attributes are automatically validated for type compatibility:
Pattern
only applies to string propertiesRange
andMultipleOf
only apply to numeric properties (int, float)Items
constraints only apply to array propertiesLength
adapts behavior:minLength
/maxLength
for strings,minItems
/maxItems
for arraysEnum
works with any property type
PHPDoc Validation Constraints
Generator supports extracting validation constraints from PHPDoc comments, providing rich validation rules directly in your generated schemas.
Supported PHPDoc Constraints
Numeric Constraints
positive-int
- Integer greater than 0negative-int
- Integer less than 0non-positive-int
- Integer less than or equal to 0non-negative-int
- Integer greater than or equal to 0int<min, max>
- Integer within a specific range
String Constraints
non-empty-string
- String with minimum length of 1numeric-string
- String containing only numeric charactersclass-string
- Valid PHP class name string
Array Constraints
non-empty-array
- Array with at least one elementnon-empty-list
- List with at least one elementarray{key: type, ...}
- Shaped arrays with specific structure
Example Usage
The generated schema will include validation constraints:
Format Support
The generator supports JSON Schema format validation through the Format
enum:
Available Formats
Format::Date
- Date format (YYYY-MM-DD)Format::Time
- Time format (HH:MM:SS)Format::DateTime
- Date-time format (ISO 8601)Format::Duration
- Duration formatFormat::Email
- Email address formatFormat::Hostname
- Hostname formatFormat::Ipv4
- IPv4 address formatFormat::Ipv6
- IPv6 address formatFormat::Uri
- URI formatFormat::UriReference
- URI reference formatFormat::Uuid
- UUID formatFormat::Regex
- Regular expression format
Additional Properties
The generator supports defining additional properties for object types using the AdditionalProperties
attribute. This
is useful for creating dynamic objects with a specific property type.
The generated schema will include additionalProperties
definitions:
Supported Value Types
The AdditionalProperties
attribute supports the following value types:
- Basic types:
'string'
,'integer'
,'number'
,'boolean'
- Object type:
'object'
(requiresvalueClass
parameter for class references) - Any type:
'mixed'
(translates toadditionalProperties: true
)
Example with Multiple Dynamic Property Types
Configuration Options
Property Data Extractors
The generator uses a modular property data extractor system that allows you to customize how validation constraints are extracted from properties:
Available Extractors:
PhpDocValidationConstraintExtractor
- Extracts constraints from PHPDoc commentsAttributeConstraintExtractor
- Extracts constraints from PHP attributesAdditionalPropertiesExtractor
- Processes additional properties settingsCompositePropertyDataExtractor
- Combines multiple extractors
Usage Examples:
Custom Property Data Extractors
You can create custom property data extractors by implementing the PropertyDataExtractorInterface
:
Integration with Valinor
The JSON Schema Generator works perfectly with the Valinor PHP package for complete data mapping and validation workflows. Valinor can validate incoming data based on the same PHPDoc constraints that the generator uses to create JSON schemas.
Installation
First, install Valinor alongside the JSON Schema Generator:
Complete Schema and Mapping Solution
Here's a complete example showing how to combine both packages:
Usage Example
Benefits of This Integration
- Consistent Validation: Both packages respect the same PHPDoc validation constraints
- Schema Generation: Generate JSON schemas for API documentation or LLM structured output
- Data Mapping: Safely convert incoming JSON data to strongly-typed PHP DTOs
- Runtime Validation: Valinor validates data against the same constraints used in schema generation
- Error Handling: Get detailed validation errors when data doesn't match your DTO structure
Real-world Example
API Endpoint Example
This integration is particularly useful for API endpoints:
Error Handling
Both packages provide detailed error information:
Testing
Contributing
Please see CONTRIBUTING for details.
License
The MIT License (MIT). Please see License File for more information.
All versions of json-schema-generator with dependencies
symfony/property-info Version ^7.2.0 || ^8.0.0
phpstan/phpdoc-parser Version ^1.33 | ^2.1
phpdocumentor/reflection-docblock Version ^5.3