Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Schema Bundle Laravel Package

bcastellano/json-schema-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bcastellano/json-schema-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Bcastellano\JsonSchemaBundle\BcastellanoJsonSchemaBundle::class => ['all' => true],
    ];
    
  2. 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
    
  3. 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());
        }
    }
    

Implementation Patterns

Workflows

  1. Request Validation

    • Use the JsonSchemaValidator service to validate incoming requests:
      $validator->validate($request->getContent(), 'request_schema');
      
    • Integrate with Symfony’s event system (e.g., 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));
          }
      }
      
  2. Response Validation

    • Validate API responses before sending:
      $responseData = ['data' => $user];
      $validator->validate(json_encode($responseData), 'response_schema');
      
  3. Schema Generation

    • Auto-generate schemas from sample requests/responses:
      php bin/console bcastellano:json-schema:generate request_sample.json request_schema
      
    • Use generated schemas for consistent validation.

Integration Tips

  • API Platform: Pair with api-platform/core for automatic schema validation in OpenAPI/Swagger docs.
  • Symfony Serializer: Combine with serializer component to validate serialized data.
  • Doctrine: Validate entity DTOs before database operations.

Gotchas and Tips

Pitfalls

  1. Schema Path Configuration

    • Ensure schemas_path in bcastellano_json_schema.yaml is correct and writable.
    • Auto-generation fails silently if the directory doesn’t exist.
  2. Circular References

    • JSON Schema doesn’t natively support circular references. Use $ref sparingly or flatten schemas.
  3. Performance

    • Avoid validating large payloads in production. Cache schemas or use lightweight validation for bulk operations.
  4. Event Listener Order

    • Place kernel.request listeners before your controllers to fail fast on invalid requests.

Debugging

  • Validation Errors: Use getErrors() to inspect failures:
    $errors = $validator->validate($data, 'schema')->getErrors();
    
  • Schema Generation: Verify generated schemas match expectations by comparing with manual definitions.

Extension Points

  1. 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']
    
  2. Dynamic Schema Loading Load schemas dynamically (e.g., from a database) by implementing SchemaLoaderInterface.

  3. OpenAPI Integration Use the bcastellano:json-schema:openapi command to sync schemas with OpenAPI specs:

    php bin/console bcastellano:json-schema:openapi
    

Tips

  • Schema Versioning: Use semantic versioning in schema filenames (e.g., v1/user_schema.json).
  • Testing: Mock JsonSchemaValidator in unit tests:
    $validator = $this->createMock(JsonSchemaValidator::class);
    $validator->method('validate')->willReturn(new ValidationResult(true, []));
    
  • CI/CD: Run schema validation in CI to catch breaking changes early.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle