philiprehberger/php-schema-validator 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/php-schema-validator

Composer 安装命令:

composer require philiprehberger/php-schema-validator

包简介

Fluent data schema validator with nested objects, arrays, and dot-notation errors

README 文档

README

Tests Latest Version on Packagist Last updated

Fluent data schema validator with nested objects, arrays, and dot-notation errors.

Requirements

  • PHP 8.2+

Installation

composer require philiprehberger/php-schema-validator

Usage

use PhilipRehberger\SchemaValidator\Schema;

$schema = Schema::object([
    'name'  => Schema::string()->min(1)->max(100),
    'email' => Schema::string()->email(),
    'age'   => Schema::int()->min(0)->max(150),
]);

$result = $schema->validateData([
    'name'  => 'Alice',
    'email' => 'alice@example.com',
    'age'   => 30,
]);

$result->passes(); // true
$result->fails();  // false
$result->errors(); // []

Nested Objects

$schema = Schema::object([
    'user' => Schema::object([
        'profile' => Schema::object([
            'email' => Schema::string()->email(),
        ]),
    ]),
]);

$result = $schema->validateData([
    'user' => ['profile' => ['email' => 'invalid']],
]);

$result->errors(); // ["user.profile.email must be a valid email address"]

Typed Arrays

$schema = Schema::object([
    'tags'  => Schema::arrayOf(Schema::string()),
    'items' => Schema::arrayOf(Schema::object([
        'id'   => Schema::int(),
        'name' => Schema::string(),
    ])),
]);

Optional and Nullable Fields

$schema = Schema::object([
    'name'     => Schema::string(),
    'nickname' => Schema::string()->optional(),  // field may be absent
    'bio'      => Schema::string()->nullable(),  // field may be null
]);

String Validators

Schema::string()->min(3)->max(50);   // length constraints
Schema::string()->email();           // email format
Schema::string()->url();             // URL format
Schema::string()->uuid();            // UUID format
Schema::string()->regex('/^\d+$/');  // custom pattern

Enum Values

Schema::enum(['draft', 'published', 'archived']);

Any Value

Schema::any();           // accepts any non-null value
Schema::any()->nullable(); // accepts anything including null

Custom Validation Rules

Add custom validation logic to any schema type using custom(). The callable receives the value and returns null if valid, or an error message string if invalid.

$schema = Schema::object([
    'username' => Schema::string()->min(3)->custom(function (string $value): ?string {
        if (str_starts_with($value, 'admin')) {
            return 'must not start with "admin"';
        }

        return null;
    }),
    'age' => Schema::int()->min(0)->custom(function (int $value): ?string {
        if ($value % 2 !== 0) {
            return 'must be an even number';
        }

        return null;
    }),
]);

$result = $schema->validateData(['username' => 'admin_user', 'age' => 25]);
$result->errors();
// ["username must not start with "admin"", "age must be an even number"]

Custom validators only run when all built-in checks pass.

Value Transformers

Use transform() to normalize a value before validation. The callable receives the raw value and returns the transformed value.

$schema = Schema::object([
    'email' => Schema::string()->email()->transform(fn (mixed $v) => strtolower(trim($v))),
    'tags'  => Schema::arrayOf(Schema::string())->transform(fn (mixed $v) => array_unique($v)),
]);

$result = $schema->validateData([
    'email' => '  Alice@Example.COM  ',
    'tags'  => ['php', 'laravel', 'php'],
]);

$result->passes(); // true — email was trimmed and lowered before validation

Transformers run before any type or constraint checks (but after the null check).

Cross-Field Validation

Use crossField() on an ObjectSchema to validate relationships between fields. Each callable receives the full data array and returns null if valid, or an error message string.

$schema = Schema::object([
    'password'         => Schema::string()->min(8),
    'password_confirm' => Schema::string(),
    'start_date'       => Schema::string(),
    'end_date'         => Schema::string(),
])->crossField(function (array $data): ?string {
    if ($data['password'] !== $data['password_confirm']) {
        return 'password_confirm must match password';
    }

    return null;
})->crossField(function (array $data): ?string {
    if ($data['start_date'] >= $data['end_date']) {
        return 'end_date must be after start_date';
    }

    return null;
});

$result = $schema->validateData([
    'password'         => 'secret123',
    'password_confirm' => 'different',
    'start_date'       => '2026-03-20',
    'end_date'         => '2026-03-10',
]);

$result->errors();
// ["password_confirm must match password", "end_date must be after start_date"]

Cross-field validators only run when all individual field validations pass.

Conditional Fields

Use when() on an ObjectSchema to conditionally require additional fields based on the value of another field.

$schema = Schema::object([
    'type' => Schema::string(),
    'email' => Schema::string()->email(),
])->when('type', 'business', [
    'company_name' => Schema::string()->min(1),
    'tax_id' => Schema::string(),
]);

// When type is 'business', company_name and tax_id are also validated
// When type is anything else, those fields are ignored

Schema Composition

Use extend() to create a new schema that combines the fields of the current schema with additional fields.

$base = Schema::object(['name' => Schema::string(), 'email' => Schema::string()->email()]);
$admin = $base->extend(['role' => Schema::string(), 'permissions' => Schema::arrayOf(Schema::string())]);
// $admin validates name, email, role, and permissions
// $base is unchanged

Custom Error Messages

Use withMessages() on a ValidationResult to replace default error messages for specific fields.

$result = $schema->validateData($data);

$result = $result->withMessages([
    'name' => 'Please enter your full name',
    'email' => 'A valid email address is required',
]);

API

Schema (static factory)

Method Returns Description
Schema::object(array $fields) ObjectSchema Create an object schema with field definitions
Schema::string() StringSchema Create a string schema
Schema::int() IntSchema Create an integer schema
Schema::float() FloatSchema Create a float schema
Schema::bool() BoolSchema Create a boolean schema
Schema::arrayOf(SchemaType $item) ArraySchema Create a typed array schema
Schema::enum(array $values) EnumSchema Create an enum schema
Schema::any() AnySchema Create a schema that accepts any value

ValidationResult

Method Returns Description
passes() bool True if validation passed
fails() bool True if validation failed
errors() array<string> All error messages
firstError() ?string First error message or null
withMessages(array $messages) ValidationResult Replace errors for matching field paths with custom messages

ObjectSchema extras

Method Description
crossField(callable $validator) Add a cross-field validator (receives full data array, returns ?string)
when(string $field, mixed $value, array $thenSchema) Conditionally validate additional fields when a field matches a value
extend(array $additionalFields) Create a new schema combining current fields with additional fields

Common Modifiers

All schema types support:

Method Description
optional() Field may be absent from the parent object
nullable() Field may be null
custom(callable $validator) Add a custom validation callback (receives value, returns ?string)
transform(callable $transformer) Transform the value before validation

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/php-schema-validator 适用场景与选型建议

philiprehberger/php-schema-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「schema」 「validator」 「fluent」 「validation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/php-schema-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/php-schema-validator 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/php-schema-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 58
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-15