masum/laravel-json-schema
Composer 安装命令:
composer require masum/laravel-json-schema
包简介
A lightweight JSON Schema builder for Laravel with fluent API
README 文档
README
A lightweight, fluent JSON Schema builder for Laravel with full validation support.
Installation
composer require masum/laravel-json-schema
Quick Start
Basic Schema Definition
use Masum\JsonSchema\Schema; $userSchema = Schema::object() ->property('id', Schema::string()->format('uuid')) ->property('name', Schema::string()->minLength(1)->maxLength(255)) ->property('email', Schema::string()->format('email')) ->property('age', Schema::number()->integer()->minimum(0)->nullable()) ->required(['id', 'name', 'email']); // Convert to JSON $json = $userSchema->toJson(); // Convert to array $array = $userSchema->toArray();
Validation
Direct Validation
$data = [ 'id' => '550e8400-e29b-41d4-a716-446655440000', 'name' => 'John Doe', 'email' => 'john@example.com' ]; $result = Schema::validate($data, $userSchema); if ($result['valid']) { // Data is valid } else { // Handle errors $errors = $result['errors']; }
Laravel Validation Rule
use Illuminate\Http\Request; use Masum\JsonSchema\Schema; public function store(Request $request) { $request->validate([ 'user_data' => [Schema::rule($userSchema)], ]); // Data is valid }
Form Request Integration
use Masum\JsonSchema\Helpers; use Illuminate\Foundation\Http\FormRequest; // Assuming FormRequest is used class StoreUserRequest extends FormRequest { public function rules() { return Helpers::createValidationRules($userSchema); } }
Advanced Usage
Compound Schemas
$schema = Schema::compound() ->anyOf([ Schema::string()->minLength(5), Schema::number()->minimum(10) ]);
Array Validation
$schema = Schema::array() ->items(Schema::object() ->property('id', Schema::string()) ->property('value', Schema::number()) ) ->minItems(1) ->maxItems(10) ->uniqueItems(true);
Custom Properties
$schema = Schema::object() ->property('id', Schema::string()) ->custom('$schema', 'http://json-schema.org/draft-07/schema#') ->custom('x-custom-property', 'custom-value');
Artisan Commands
Create a New Schema
php artisan make:schema UserSchema
Create Example Schema
php artisan make:schema UserSchema --example
Validate Data
# From argument php artisan schema:validate UserSchema '{"name": "John", "email": "john@example.com"}' # From file php artisan schema:validate UserSchema --file=user-data.json # From stdin echo '{"name": "John"}' | php artisan schema:validate UserSchema
Configuration
Publish the configuration file:
php artisan vendor:publish --provider="Masum\JsonSchema\SchemaServiceProvider" --tag="json-schema-config"
Testing
composer test
Features
- ✅ Fluent, expressive API
- ✅ Full JSON Schema Draft-07 support
- ✅ Laravel validation integration
- ✅ Compound types (anyOf, oneOf, allOf, not)
- ✅ Custom properties and extensions
- ✅ Artisan commands for schema management
- ✅ Comprehensive validation with detailed errors
- ✅ Nullable field support
- ✅ Format validation (email, URL, UUID, dates)
- ✅ Array and object validation
- ✅ Configuration-driven behavior
License
This package is open-source software licensed under the MIT license.
Example Schemas
Create schemas/ExampleUserSchema.php
<?php /** * Example User Schema * * Demonstrates various JSON Schema features and validation rules. */ use Masum\JsonSchema\Schema; return Schema::object() ->property('id', Schema::string()->format('uuid')->description('Unique user identifier')) ->property('name', Schema::string()->minLength(1)->maxLength(255)->description('User full name')) ->property('email', Schema::string()->format('email')->description('User email address')) ->property('age', Schema::number()->integer()->minimum(0)->maximum(150)->nullable()->description('User age')) ->property('roles', Schema::array()->items(Schema::string()->enum(['admin', 'user', 'editor']))->minItems(1)->description('User roles')) ->property('metadata', Schema::object()->additionalProperties(true)->description('Additional user metadata')) ->property('created_at', Schema::string()->format('date-time')->description('Creation timestamp')) ->required(['id', 'name', 'email', 'created_at']) ->custom('$schema', 'http://json-schema.org/draft-07/schema#') ->custom('title', 'User Schema') ->custom('description', 'Schema for validating user data in the application') ->comment('This schema is used for user data validation across the application');
Examples with API Resources
This section demonstrates how to integrate the laravel-json-schema package with Laravel API Resources for robust API development and validation, as found in the examples/ directory.
Structure
examples/app/Http/Resources/: Contains various Laravel API Resource classes (UserResource,UserCollection,ProfileResource,PostResource,RoleResource,CategoryResource,CommentResource). These resources showcase how to define JSON Schemas directly within the resource classes usingstatic::schema()methods, handle relationships, conditional attributes, and include metadata.examples/app/Http/Controllers/: Includes an exampleUserControllerdemonstrating how to use the resources for listing, storing, showing, updating, and deleting users. It also shows how to validate incoming request data against a defined JSON Schema.examples/app/Models/: Contains a minimalUser.phpmodel with placeholder relationships and methods to support the examples in the resources and controller.examples/api-responses/: Provides example JSON response payloads for both single resources and resource collections, illustrating how the integrated schemas and metadata appear in the API output.
Key Concepts Demonstrated
- Schema Definition within Resources: How to define a JSON Schema directly within your
JsonResourceclasses using a staticschema()method. - Resource Validation: Using
Masum\JsonSchema\Schema::validate()to validate incoming request data against a resource's defined schema in your controllers. - Resource Collections: Utilizing
ResourceCollectionfor consistent pagination and metadata handling. - Conditional Attributes: Employing
$this->when()and$this->whenLoaded()for efficient data loading and conditional attribute inclusion. - Relationships: Handling nested resources and collections for related models.
- API Metadata: Adding schema definitions, versioning, and other useful metadata to API responses via the
with()method. - Artisan Commands: Although not explicitly shown in code here, the
make:resourcecommand is a prerequisite for creating these files.
To run these examples, you would typically set up a Laravel application and integrate the laravel-json-schema package. You would also need to define routes that point to the UserController methods.
Final Testing Suite
Create tests/IntegrationTest.php
<?php namespace Masum\JsonSchema\Tests; use Masum\JsonSchema\Schema; use Masum\JsonSchema\Helpers; class IntegrationTest extends TestCase { public function test_can_use_in_laravel_validation(): void { $schema = Schema::object() ->property('email', Schema::string()->format('email')) ->required(['email']); $validator = \Validator::make( ['data' => ['email' => 'test@example.com']], ['data' => [Schema::rule($schema)]] ); $this->assertTrue($validator->passes()); } public function test_can_convert_schema_to_laravel_rules(): void { $schema = Schema::object() ->property('email', Schema::string()->format('email')) ->property('age', Schema::number()->minimum(18)) ->required(['email']); $rules = Helpers::schemaToRules($schema); $this->assertArrayHasKey('email', $rules); $this->assertArrayHasKey('age', $rules); $this->assertContains('email', $rules['email']); } public function test_artisan_commands_are_registered(): void { $this->assertTrue(\Artisan::has('make:schema')); $this->assertTrue(\Artisan::has('schema:validate')); } }
Run Final Tests
# Run all tests ./vendor/bin/phpunit # Test code coverage (if configured) ./vendor/bin/phpunit --coverage-html coverage
masum/laravel-json-schema 适用场景与选型建议
masum/laravel-json-schema 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 30 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「fluent」 「validation」 「laravel」 「json-schema」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 masum/laravel-json-schema 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 masum/laravel-json-schema 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 masum/laravel-json-schema 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Presentation and Formatting helper with nice fluent interface.
Traits gathering fluent syntax common methods
A modern, fluent HTTP client. Forked from Mashape, reimagined by Nidux, and open-sourced for the PHP community.
A PSR-7 compatible library for making CRUD API endpoints
A fluent PHP CURL wrapper
Adds request-parameter validation to the SLIM 3.x PHP framework
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-30