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

Php Json Schema Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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.

  2. 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);
    
  3. Where to Look First

    • Validator Class: Core class for validation logic (src/Validator.php).
    • Exceptions: Custom exceptions for validation errors (src/Exception/).
    • Examples: Check tests/ for usage patterns (if available).

Implementation Patterns

Common Workflows

  1. 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);
    
  2. 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
    }
    
  3. 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);
        }
    }
    
  4. 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());
    
  5. Dynamic Schema Loading Load schemas dynamically from a database or API:

    $schema = json_decode(SchemaModel::find($id)->schema, true);
    $validator->validate($schema, $data);
    

Gotchas and Tips

Pitfalls

  1. Schema Format Strictness

    • The package expects strict JSON Schema Draft 4/6/7 compliance. Invalid schemas (e.g., missing type) will throw exceptions.
    • Fix: Validate schemas using JSON Schema Validator before using this package.
  2. Error Handling

    • Errors are returned as a string (e.g., "Property 'age' is missing"). Parse carefully if integrating with Laravel’s validation messages.
    • Tip: Extend the Validator class to return structured errors:
      class CustomValidator extends Validator {
          public function getErrors(): array {
              return explode("\n", parent::getErrors());
          }
      }
      
  3. Performance with Large Schemas

    • Complex schemas (e.g., nested allOf, anyOf) may slow validation.
    • Tip: Cache compiled schemas if reused frequently:
      $schemaCache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
      $schema = $schemaCache->get('user_schema', function() use ($schemaFile) {
          return json_decode(file_get_contents($schemaFile), true);
      });
      
  4. Type Coercion

    • The package does not coerce types (e.g., "5"5). Use Laravel’s Request::validate() for this if needed.
  5. Dependency Conflicts

    • If using Laravel, ensure no conflicts with laravel/json-schema or spatie/json-schema.
    • Tip: Check composer why-not to resolve version conflicts.

Debugging Tips

  1. Enable Verbose Errors

    $validator = new Validator();
    $validator->setVerbose(true); // Shows full schema path in errors
    
  2. 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()
        ]);
    }
    
  3. Test Edge Cases

    • Test with:
      • Empty objects/arrays.
      • null values.
      • Deeply nested objects.
      • Custom formats (e.g., format: "date-time").

Extension Points

  1. 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
            };
        }
    }
    
  2. Plugin System Use Laravel’s service provider to bind a custom validator:

    // config/app.php
    'bindings' => [
        Validator::class => function ($app) {
            return new CustomValidator();
        },
    ];
    
  3. 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());
            }
        }
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor