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 Runtime Laravel Package

jane-php/json-schema-runtime

Runtime support library for code generated by Jane JsonSchema. Provides shared classes used by Jane-generated PHP clients and models (serialization, validation, etc.). See Jane docs for usage and contribute via the main janephp repository.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Schema-Driven Validation: Fits Laravel’s API-first and contract-first development, aligning with OpenAPI/Swagger workflows. Ideal for enforcing request/response schemas, form validation, and data pipeline integrity without custom logic.
  • Jane Ecosystem Synergy: If already using Jane JsonSchema for code generation, this runtime provides a zero-overhead execution layer, reducing duplication. For standalone use, it offers a lightweight alternative to Symfony’s validator.
  • Laravel Integration Points:
    • Middleware: Validate requests early in the pipeline (e.g., ValidateJsonSchema).
    • Form Requests: Replace rules() with schema validation in Illuminate\Foundation\Http\FormRequest.
    • API Resources: Enforce response schemas in JsonResource::toArray().
    • Events/Jobs: Validate payloads in Illuminate\Queue\Jobs\Job::handle().
  • Performance Considerations:
    • Compiled Schemas: If using Jane’s generator, schemas are pre-compiled, reducing runtime overhead.
    • Cold Start: First validation may have latency; cache compiled schemas if needed.

Integration Feasibility

  • Laravel-Specific Patterns:
    • Service Container: Bind validator as a singleton for reuse.
    • Facades: Create a Schema facade for cleaner syntax (e.g., Schema::validate($data, 'user')).
    • Testing: Integrate with Laravel’s HttpTests and Pest for schema validation assertions.
  • Database/ORM:
    • Validate Eloquent model attributes before save() or create().
    • Useful for API resources to ensure consistent responses.
  • Third-Party Tools:
    • Lumen: Lightweight alternative for microservices.
    • Livewire/Inertia: Validate form submissions before server-side processing.
    • Sanctum/Passport: Validate JWT claims or API token payloads.

Technical Risk

  • Abandoned Maintenance:
    • Last release in 2018 with no dependents is a red flag. Mitigation:
      • Fork the repo to backport fixes (e.g., PHP 8.2+ support).
      • Use as a runtime-only validator to avoid generator lock-in.
    • Dependency Risks:
      • league/uri v6/7 may conflict with Laravel’s symfony/routing.
      • symfony/serializer v8.x requires Laravel 10+ (released 2023).
  • Schema Complexity:
    • JSON Schema’s expressiveness may lead to over-engineering for simple cases. Compare with Laravel’s built-in validation for trivial rules.
  • Error Handling:
    • Default validator lacks detailed error messages. Extend with custom exceptions or integrate with Laravel’s ValidationException.
  • Performance:
    • Runtime validation adds latency. Benchmark against alternatives like:
      • symfony/validator (feature-rich, actively maintained).
      • zod-php/zod (modern, type-safe).
      • respect/validation (lightweight).

Key Questions

  1. Why Jane Over Alternatives?
    • Is the team already using Jane JsonSchema? If not, evaluate symfony/validator or zod-php/zod for better maintenance.
  2. Laravel Version Support:
    • Test compatibility with Laravel 10/11 (PHP 8.1+). Downgrade symfony/serializer if needed for Laravel 9.
  3. Schema Management:
    • How will schemas be versioned and deployed? (e.g., config/schemas/v1/, Git submodules).
  4. Fallback Strategy:
    • Plan for graceful degradation if the package fails (e.g., fall back to Validator::make()).
  5. Team Expertise:
    • Does the team have JSON Schema experience? Budget for ramp-up if adopting from scratch.
  6. Dynamic Schemas:
    • Does the use case require runtime schema updates? If yes, this package is not suitable (no dynamic support).

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Request Validation: Replace or augment Illuminate\Validation\Validator with schema-driven rules.
    • API Contracts: Enforce OpenAPI/Swagger schemas for REST/GraphQL APIs.
    • Form Handling: Validate Livewire/Inertia submissions before server-side processing.
  • Service Layer:
    • Bind validator as a singleton in AppServiceProvider:
      $this->app->singleton(JsonSchemaValidator::class, fn() => new \Jane\JsonSchemaRuntime\Validator());
      
    • Create a facade for cleaner syntax:
      Schema::validate($request->all(), 'schemas/user-request.yaml');
      
  • Testing:
    • Integrate with Laravel’s HttpTests:
      public function test_user_creation_validates_schema() {
          $response = $this->postJson('/users', ['name' => 'John']);
          $response->assertValid(); // Uses Laravel’s validation helpers
      }
      
    • Use Pest for schema validation assertions:
      test('schema validation fails on invalid data', function () {
          $validator = app(JsonSchemaValidator::class);
          expect($validator->validate(['invalid' => 'data'], 'schemas/user-request.yaml'))
              ->toBeFalse();
      });
      

Migration Path

  1. Pilot Phase:
    • Start with non-critical endpoints (e.g., admin panels, internal APIs).
    • Replace 1–2 FormRequest classes with schema validation.
  2. Incremental Rollout:
    • Phase 1: Validate API requests (e.g., POST /api/users).
    • Phase 2: Enforce response schemas (e.g., GET /api/users/{id}).
    • Phase 3: Extend to database operations (e.g., Eloquent model validation).
  3. Tooling Integration:
    • Laravel Forge/Envoyer: Deploy schema files alongside code.
    • Laravel Scout: Validate search payloads (e.g., Algolia queries).
    • Laravel Horizon: Validate queue job payloads.

Compatibility

  • PHP 8.1+: Confirmed by composer.json, but test with PHP 8.2/8.3 for BC breaks.
  • Laravel 9/10/11:
    • Laravel 10+: Preferred for symfony/serializer v8.x compatibility.
    • Laravel 9: Downgrade symfony/serializer to v6.x if needed.
  • Schema Formats:
    • Supports JSON/YAML. Use YAML for readability in Laravel config (e.g., config/schemas/api.yaml).
  • Dependency Conflicts:
    • Symfony Components: Laravel already uses symfony/console, symfony/http-foundation, etc. Test for version skew.
    • League URI: Ensure no conflicts with Laravel’s Illuminate\Support\Facades\URL.

Sequencing

  1. Schema Design:
    • Define schemas in config/schemas/ (YAML/JSON).
    • Example: config/schemas/user-request.yaml for POST /users.
  2. Validator Service:
    // app/Services/JsonSchemaValidator.php
    class JsonSchemaValidator {
        public function validate(array $data, string $schemaPath): bool {
            $schema = Yaml::parseFile($schemaPath);
            $validator = new \Jane\JsonSchemaRuntime\Validator();
            return $validator->validate($data, $schema);
        }
    }
    
  3. Middleware Integration:
    // app/Http/Middleware/ValidateJsonSchema.php
    public function handle(Request $request, Closure $next) {
        $validator = app(JsonSchemaValidator::class);
        $schemaPath = "schemas/{$request->route()->getName()}.yaml";
        if (!$validator->validate($request->all(), $schemaPath)) {
            abort(422, 'Schema validation failed');
        }
        return $next($request);
    }
    
  4. Form Request Integration:
    // app/Http/Requests/StoreUserRequest.php
    public function authorize(): bool { return true; }
    public function rules(): array { return []; } // Empty; use schema instead
    public function validateSchema(): void {
        $validator = app(JsonSchemaValidator::class);
        if (!$validator->validate($this->all(), 'schemas/user-request.yaml')) {
            abort(422, 'Invalid request data');
        }
    }
    
  5. Testing:
    • Write Pest/PhpUnit tests for each schema-validated endpoint.
    • Example:
      test('schema validation rejects invalid data', function () {
          $response = $this->postJson('/users', ['invalid' => 'data']);
          $response->assertUnprocessable();
      });
      
  6. Monitoring:
    • Log schema validation failures (e.g., `Mon
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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