event-engine/php-json-schema
Event Engine JSON Schema package for PHP. Generate/use JSON Schema with ImmutableRecord type detection. v1.x detects types via method return hints (PHP 7.2–7.3); v2.x uses PHP 7.4+ typed properties for improved schema support.
Installation
composer require event-engine/php-json-schema
Add to composer.json if not auto-loaded:
"autoload": {
"psr-4": {
"App\\": "app/",
"EventEngine\\JsonSchema\\": "vendor/event-engine/php-json-schema/src/"
}
}
Run composer dump-autoload.
First Use Case: Schema Validation
use EventEngine\JsonSchema\Validator;
$validator = new Validator();
$schema = [
"type" => "object",
"properties" => [
"name" => ["type" => "string"],
"age" => ["type" => "integer"]
],
"required" => ["name"]
];
$data = ['name' => 'John', 'age' => 30];
$isValid = $validator->validate($schema, $data);
Where to Look First
src/Validator.php).src/Exception/).tests/ for usage patterns (if available).Schema Definition
Define schemas in PHP arrays or external JSON files (e.g., config/schemas/user.json):
$schema = json_decode(file_get_contents('config/schemas/user.json'), true);
Validation in Controllers
public function store(Request $request) {
$validator = new Validator();
$schema = require __DIR__ . '/schemas/user-create.json';
if (!$validator->validate($schema, $request->all())) {
throw new \RuntimeException('Invalid input: ' . $validator->getErrors());
}
// Proceed with logic
}
Reusable Schema Validation Create a service class for shared schemas:
class UserSchemaValidator {
protected $validator;
public function __construct(Validator $validator) {
$this->validator = $validator;
}
public function validateCreate(array $data): bool {
$schema = require __DIR__ . '/schemas/user-create.json';
return $this->validator->validate($schema, $data);
}
}
Integration with Laravel Request Validation Combine with Laravel’s built-in validation for hybrid approaches:
$request->validate([
'name' => 'required|string',
'age' => 'integer',
]);
// Additional custom schema validation
$validator = new Validator();
$customSchema = [...];
$validator->validate($customSchema, $request->validated());
Dynamic Schema Loading Load schemas dynamically from a database or API:
$schema = json_decode(SchemaModel::find($id)->schema, true);
$validator->validate($schema, $data);
Schema Format Strictness
type) will throw exceptions.Error Handling
"Property 'age' is missing"). Parse carefully if integrating with Laravel’s validation messages.Validator class to return structured errors:
class CustomValidator extends Validator {
public function getErrors(): array {
return explode("\n", parent::getErrors());
}
}
Performance with Large Schemas
allOf, anyOf) may slow validation.$schemaCache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
$schema = $schemaCache->get('user_schema', function() use ($schemaFile) {
return json_decode(file_get_contents($schemaFile), true);
});
Type Coercion
"5" → 5). Use Laravel’s Request::validate() for this if needed.Dependency Conflicts
laravel/json-schema or spatie/json-schema.composer why-not to resolve version conflicts.Enable Verbose Errors
$validator = new Validator();
$validator->setVerbose(true); // Shows full schema path in errors
Log Schema Validation
try {
$validator->validate($schema, $data);
} catch (\EventEngine\JsonSchema\Exception\ValidationException $e) {
\Log::error('Schema validation failed:', [
'schema' => $schema,
'data' => $data,
'error' => $e->getMessage()
]);
}
Test Edge Cases
null values.format: "date-time").Custom Keywords Extend the validator to support custom JSON Schema keywords:
class CustomValidator extends Validator {
protected function registerCustomKeywords() {
$this->keywords['customKeyword'] = function ($data, $schema) {
// Custom logic
};
}
}
Plugin System Use Laravel’s service provider to bind a custom validator:
// config/app.php
'bindings' => [
Validator::class => function ($app) {
return new CustomValidator();
},
];
Integration with Laravel Form Requests Create a base request class for schema validation:
abstract class SchemaValidatedRequest extends FormRequest {
public function validateSchema(array $schema): void {
$validator = app(Validator::class);
if (!$validator->validate($schema, $this->all())) {
throw new \RuntimeException($validator->getErrors());
}
}
}
How can I help you explore Laravel packages today?