dsheiko/validate 问题修复 & 功能扩展

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

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

dsheiko/validate

Composer 安装命令:

composer require dsheiko/validate

包简介

High-performance, secure validation library for Design by Contract programming. Validate primitive and complex types with chainable validators, contract-based validation, and comprehensive security features.

README 文档

README

Latest Stable Version Total Downloads License

Extendable, high-performance validation library for testing primitive and complex types against a contract. Designed for Design by Contract programming and comprehensive input validation in PHP applications.

Installation

Require as a composer dependency:

composer require "dsheiko/validate"

Requirements

  • PHP >= 7.0.0
  • No external dependencies

Key Features

🎯 Core Capabilities

  • Validators are dead simple to extend - Create custom validators by implementing ValidateInterface
  • Design by Contract support - Validate preconditions and postconditions with Validate::contract()
  • Validator chaining - Chain multiple validators for fluent validation syntax
  • Direct assertion access - Use validators as direct assertions in your code
  • Complex type validation - Support for nested arrays, associative arrays, and key-value structures
  • Exception-based error handling - Specific exception types for different validation failures

🔐 Security Features (v1.2.0+)

  • Credit card validation - Implements Luhn algorithm for genuine card validation
  • ReDoS protection - Length constraints prevent regular expression denial of service attacks
  • Email length validation - RFC 5321 compliant length constraints
  • Input sanitization - Validators properly handle edge cases and malicious input

⚡ Performance Features

  • Factory caching - 30-50% faster validation chains
  • Optimized validators - 10-15% faster UUID and string validation
  • Efficient loops - Removed closure overhead for 5-10% improvement
  • Minimal overhead - Fast validation suitable for high-traffic applications

Quick Start

<?php
use \Dsheiko\Validate;

// Simple validation
$validate = new Validate();
$validate->IsString("hello")
         ->IsInt(42, ["min" => 0, "max" => 100])
         ->IsEmailAddress("user@example.com");

if (!$validate->isValid()) {
    foreach ($validate->getMessages() as $message) {
        echo $message . "\n";
    }
}

// Contract-based validation
Validate::contract([
    "email" => ["user@example.com", "IsEmailAddress"],
    "age" => [25, ["IsInt" => ["min" => 18, "max" => 120]]],
]);

// Map validation
Validate::map($data, [
    "username" => ["mandatory", "IsString" => ["minLength" => 3, "maxLength" => 20]],
    "email" => ["mandatory", "IsEmailAddress"],
    "age" => ["optional", "IsInt" => ["min" => 0, "max" => 150]],
]);

Security

Recent Security Improvements (v1.2.0)

This library has been updated with critical security fixes:

  1. Credit Card Validation - Now implements the Luhn algorithm to properly validate credit card numbers. Invalid cards that previously passed regex validation will now be correctly rejected.

  2. ReDoS Protection - Added length constraints and optimized regex patterns to prevent Regular Expression Denial of Service attacks.

  3. Email Validation - Enforces RFC 5321 email length constraints (maximum 254 characters) to prevent DoS attacks.

See CHANGELOG.md for detailed security fixes in v1.2.0.

Best Practices

  • Always validate user input - Use this library to validate all untrusted input
  • Use contract validation - Catch errors early with Design by Contract validation
  • Validate early - Validate input at the application boundary
  • Handle exceptions - Catch and properly handle validation exceptions

Performance

Benchmarks (v1.2.0)

The library has been optimized for high-performance validation:

  • Validation chains: 30-50% faster with factory caching
  • UUID validation: 10-15% faster with pre-checks
  • Contract validation: 5-10% faster with optimized loops
  • Factory calls (1000x): 0.14ms

Performance Tips

  1. Use validation contracts for bulk validation
  2. Chain multiple validators instead of separate checks
  3. Validate at the boundary of your application
  4. Consider using map validation for complex data structures

See CHANGELOG.md for performance improvement details in v1.2.0.

Usage

Examples

Design by Contract Validation

<?php
use \Dsheiko\Validate;

function login($email, $password)
{
    // Validate preconditions using contract
    Validate::contract([
        "email" => [$email, "IsEmailAddress"],
        "password" => [$password, ["IsString" => ["minLength" => 6, "maxLength" => 32, "notEmpty" => true]]],
    ]);
    
    // Perform login logic...
    
    // Validate postconditions if needed
    Validate::contract([
        "session_id" => [$sessionId, "IsUuid"],
    ]);
}

Potential exceptions:

  • Dsheiko\Validate\IsEmailAddress\Exception
  • Dsheiko\Validate\IsString\Exception
  • Dsheiko\Validate\IsString\MinLength\Exception
  • Dsheiko\Validate\IsString\MaxLength\Exception

Error messages:

  • Parameter "email" validation failed: "invalid@..is not a valid email address
  • Parameter "password" validation failed: "123" is too short; must be more than 6 chars

Map Validation

<?php
use \Dsheiko\Validate;

$formData = [
    "username" => "john_doe",
    "email" => "john@example.com",
    "password" => "secure_password",
    "age" => 28,
    "newsletter" => true,
];

Validate::map($formData, [
    "username" => ["mandatory", "IsString" => ["minLength" => 3, "maxLength" => 50]],
    "email" => ["mandatory", "IsEmailAddress"],
    "password" => ["mandatory", ["IsString" => ["minLength" => 8, "maxLength" => 128, "notEmpty" => true]]],
    "age" => ["optional", "IsInt" => ["min" => 0, "max" => 150]],
    "newsletter" => ["optional", "IsBool"],
    "phone" => ["optional", "IsString"],  // Not in data, optional - OK
]);

Exception messages:

  • Property "email" validation failed: "invalid.." is not a valid email address
  • Property "age" validation failed: 200 is too high; must be less than 150

Validator Chaining

<?php
use \Dsheiko\Validate;

$validate = new Validate();
$validate->IsString("test@example.com")
         ->IsEmailAddress("test@example.com")
         ->IsString("password123")
         ->IsInt(25, ["min" => 18, "max" => 120]);

if (!$validate->isValid()) {
    // Handle validation errors
    $messages = $validate->getMessages();
}

Available Validators

Core validators included:

  • IsString - Validates string type with length constraints
  • IsInt - Validates integer type with min/max constraints
  • IsBool - Validates boolean type
  • IsArray - Validates array type
  • IsAssocArray - Validates associative array type
  • IsEmailAddress - Validates email address (RFC 5321 compliant)
  • IsUrl - Validates URL format
  • IsUuid - Validates UUID v4 format
  • IsIp - Validates IPv4 and IPv6 addresses
  • IsAlpha - Validates alphabetic characters only
  • IsAlnum - Validates alphanumeric characters
  • IsCreditCard - Validates credit card number with Luhn algorithm
  • NotEmpty - Validates non-empty values

License

MIT License - see LICENSE file for details

dsheiko/validate 适用场景与选型建议

dsheiko/validate 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 221 次下载、GitHub Stars 达 15, 最近一次更新时间为 2017 年 12 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 dsheiko/validate 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 221
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 15
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 15
  • Watchers: 2
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-12-08