Installation
composer require bcastellano/json-schema-bundle
Add the bundle to config/bundles.php:
return [
// ...
Bcastellano\JsonSchemaBundle\BcastellanoJsonSchemaBundle::class => ['all' => true],
];
Configure Schema Paths
Update config/packages/bcastellano_json_schema.yaml:
bcastellano_json_schema:
schemas_path: '%kernel.project_dir%/config/schemas'
auto_generate: true # Enable auto-generation of schemas from requests/responses
First Validation Use Case
Create a schema file (e.g., config/schemas/user_schema.json):
{
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "email"]
}
Validate a request in a controller:
use Bcastellano\JsonSchemaBundle\Validator\JsonSchemaValidator;
public function createUser(Request $request, JsonSchemaValidator $validator)
{
$schema = $validator->validate($request->getContent(), 'user_schema');
if ($schema->isValid()) {
// Process valid data
} else {
throw new \RuntimeException('Invalid request: ' . $schema->getErrors());
}
}
Request Validation
JsonSchemaValidator service to validate incoming requests:
$validator->validate($request->getContent(), 'request_schema');
kernel.request) to auto-validate:
# config/services.yaml
services:
App\EventListener\JsonSchemaListener:
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
// src/EventListener/JsonSchemaListener.php
public function onKernelRequest(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
$validator = $this->container->get('bcastellano_json_schema.validator');
$schema = $validator->validate($request->getContent(), 'request_schema');
if (!$schema->isValid()) {
$event->setResponse(new JsonResponse(['error' => $schema->getErrors()], 400));
}
}
Response Validation
$responseData = ['data' => $user];
$validator->validate(json_encode($responseData), 'response_schema');
Schema Generation
php bin/console bcastellano:json-schema:generate request_sample.json request_schema
api-platform/core for automatic schema validation in OpenAPI/Swagger docs.serializer component to validate serialized data.Schema Path Configuration
schemas_path in bcastellano_json_schema.yaml is correct and writable.Circular References
$ref sparingly or flatten schemas.Performance
Event Listener Order
kernel.request listeners before your controllers to fail fast on invalid requests.getErrors() to inspect failures:
$errors = $validator->validate($data, 'schema')->getErrors();
Custom Validators Extend the validator to support custom keywords:
// src/Validator/CustomValidator.php
use Bcastellano\JsonSchemaBundle\Validator\JsonSchemaValidatorInterface;
class CustomValidator implements JsonSchemaValidatorInterface
{
public function validate($data, string $schemaName): ValidationResult
{
// Custom logic
}
}
Register in services.yaml:
services:
App\Validator\CustomValidator:
tags: ['bcastellano_json_schema.validator']
Dynamic Schema Loading
Load schemas dynamically (e.g., from a database) by implementing SchemaLoaderInterface.
OpenAPI Integration
Use the bcastellano:json-schema:openapi command to sync schemas with OpenAPI specs:
php bin/console bcastellano:json-schema:openapi
v1/user_schema.json).JsonSchemaValidator in unit tests:
$validator = $this->createMock(JsonSchemaValidator::class);
$validator->method('validate')->willReturn(new ValidationResult(true, []));
How can I help you explore Laravel packages today?