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

jane-php/json-schema

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require jane-php/json-schema
    composer require jane-php/json-schema-runtime  # For runtime validation
    
  2. Define a JSON Schema: Create a schema file (e.g., config/schemas/user.schema.json):

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "User",
      "type": "object",
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "string" },
        "email": { "type": "string", "format": "email" }
      },
      "required": ["id", "name"]
    }
    
  3. Generate PHP Model: Use the generator to create a class from the schema:

    use Jane\JsonSchema\Generator;
    
    $generator = new Generator();
    $models = $generator->generateFromFile('config/schemas/user.schema.json');
    file_put_contents('app/Models/Generated/User.php', $models->getCode());
    
  4. Use the Generated Model: The generated class will include:

    • Type-safe properties ($id, $name, $email).
    • Serialization/deserialization methods (JsonSerializable, Arrayable).
    • Validation logic (via jane-php/json-schema-runtime).

    Example usage:

    use App\Models\Generated\User;
    
    $userData = ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'];
    $user = User::fromArray($userData); // Deserialize
    $json = $user->toJson(); // Serialize
    
  5. Integrate with Laravel:

    • Use the generated model in FormRequest for validation:
      use Jane\JsonSchemaRuntime\Validator\Validator;
      
      public function rules()
      {
          return [
              'data' => ['required', function ($attribute, $value, $fail) {
                  $schema = file_get_contents('config/schemas/user.schema.json');
                  if (!Validator::validate($value, $schema)) {
                      $fail('Invalid user data: ' . Validator::getErrors());
                  }
              }]
          ];
      }
      

Implementation Patterns

Workflows

  1. Schema-Driven API Development:

    • Store schemas in config/schemas/ or version-controlled files.
    • Generate models during composer install or via a custom artisan command:
      // app/Console/Commands/GenerateModels.php
      use Jane\JsonSchema\Generator;
      use Symfony\Component\Filesystem\Filesystem;
      
      class GenerateModels extends Command
      {
          protected $signature = 'schema:generate';
          protected $description = 'Generate models from all JSON schemas';
      
          public function handle()
          {
              $fs = new Filesystem();
              $generator = new Generator();
      
              foreach (glob('config/schemas/*.schema.json') as $schemaFile) {
                  $models = $generator->generateFromFile($schemaFile);
                  $fs->dumpFile(
                      str_replace('schemas/', 'Models/Generated/', $schemaFile),
                      $models->getCode()
                  );
              }
          }
      }
      
  2. Validation Layer:

    • Replace or extend Laravel’s Validator with Jane’s runtime validator:
      // app/Services/SchemaValidator.php
      use Jane\JsonSchemaRuntime\Validator\Validator;
      
      class SchemaValidator
      {
          public static function validate(array $data, string $schemaPath): bool
          {
              $schema = file_get_contents($schemaPath);
              return Validator::validate($data, $schema);
          }
      }
      
    • Use in FormRequest:
      public function validateResolved()
      {
          if (!SchemaValidator::validate($this->input(), 'config/schemas/user.schema.json')) {
              $this->fail(SchemaValidator::getErrors());
          }
      }
      
  3. API Resources:

    • Generate serializers for Laravel’s JsonResource:
      // app/Http/Resources/UserResource.php
      use App\Models\Generated\User;
      use Illuminate\Http\Resources\Json\JsonResource;
      
      class UserResource extends JsonResource
      {
          public function toArray($request)
          {
              return User::fromArray($this->resource)->toArray();
          }
      }
      
  4. Custom Formats:

    • Extend Jane’s support for custom formats (e.g., Laravel’s date format):
      use Jane\JsonSchema\Format\Format;
      
      Format::add('date', function ($value) {
          return Carbon::parse($value)->format('Y-m-d');
      });
      

Integration Tips

  • Symfony Compatibility:

    • Use symfony/serializer for advanced serialization needs:
      use Symfony\Component\Serializer\SerializerInterface;
      
      $serializer = app(SerializerInterface::class);
      $user = $serializer->deserialize($json, User::class, 'json');
      
  • Laravel Events:

    • Trigger model regeneration on schema file changes:
      // app/Providers/AppServiceProvider.php
      use Symfony\Component\Filesystem\Filesystem;
      
      public function boot()
      {
          if ($this->app->environment('local')) {
              Storage::disk('local')->delete('app/Models/Generated');
              $this->call('schema:generate');
          }
      }
      
  • Testing:

    • Mock generated classes in tests:
      $mockUser = Mockery::mock(User::class);
      $mockUser->shouldReceive('toArray')->andReturn(['id' => 1, 'name' => 'Test']);
      
  • Caching:

    • Cache generated classes to avoid regeneration on every request:
      if (!file_exists('bootstrap/cache/generated_models.php')) {
          $this->call('schema:generate');
          file_put_contents('bootstrap/cache/generated_models.php', '<?php // Generated models');
      }
      

Gotchas and Tips

Pitfalls

  1. Stale Code Generation:

    • Generated classes may become outdated if schemas change without regeneration.
    • Fix: Add a pre-commit hook or CI check to verify schemas match generated models.
  2. Namespace Conflicts:

    • Generated classes may clash with existing Laravel classes.
    • Fix: Use a dedicated namespace (e.g., App\Models\Generated) and exclude from autoloading:
      // composer.json
      "autoload-exclude": ["app/Models/Generated/"]
      
  3. Circular References:

    • Complex schemas with circular references may cause infinite loops.
    • Fix: Limit recursion depth in the generator or use $ref handling:
      $generator->setMaxRefDepth(5);
      
  4. Runtime Validation Overhead:

    • Jane’s runtime validator may slow down requests if overused.
    • Fix: Cache validation results or use it selectively (e.g., only for critical APIs).
  5. PHP 8.1+ Compatibility:

    • Some older Jane versions may not support PHP 8.1 features (e.g., union types).
    • Fix: Patch the generator or use a fork like spatie/fork-jane-json-schema.
  6. Symfony Dependencies:

    • Heavy reliance on Symfony components may bloat your app.
    • Fix: Use Laravel’s native alternatives where possible (e.g., Carbon instead of symfony/options-resolver).

Debugging

  1. Validation Errors:

    • Enable detailed error reporting:
      Validator::setErrorFormatter(function ($errors) {
          return json_encode($errors, JSON_PRETTY_PRINT);
      });
      
  2. Generation Failures:

    • Check the generator’s debug output:
      $generator->setDebug(true);
      
  3. Schema Parsing Issues:

Tips

  1. Partial Generation:

    • Generate only specific schemas:
      php artisan schema:generate config/schemas/user.schema.json
      
  2. Custom Traits:

    • Extend generated classes with Laravel-specific traits:
      // app/Models/Generated/User.php (after generation)
      use Illuminate\Foundation\Auth\User as Authenticatable;
      
      class User extends Authenticatable implements JsonSerializable
      {
          // Generated properties/methods
      }
      
  3. OpenAPI Integration:

    • Generate schemas from OpenAPI specs using zircote/swagger-php, then feed them to Jane:
      $openApi = \OpenApi\Generator::scan(['app/Http/Controllers']);
      $schema = $openApi->toJson();
      file_put_contents('config/schemas/api.schema.json', $schema);
      
  4. Performance Optimization:

    • Pre-compile generated classes:
      php artisan optimize:clear
      
  5. Schema Versioning:

    • Use semantic versioning for schemas (e.g
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