highperapp/validator

High-performance data validation with Rust FFI acceleration, AMPHP parallel processing, and pure PHP fallback

dev-main 2025-10-03 03:33 UTC

This package is auto-updated.

Last update: 2025-10-03 12:01:18 UTC


README

A high-performance validation library for the HighPerApp ecosystem with triple-engine architecture: Rust FFI → AMPHP → Pure PHP fallback.

Features

  • Interface-driven architecture - No abstract classes or final keywords
  • Hybrid engine architecture - Rust FFI + UV → AMPHP + UV → Pure PHP fallback
  • UV extension detection - Automatic detection and performance optimization
  • Comprehensive validation middleware - PSR-15 compatible HTTP middleware
  • Environment-based configuration - 35+ configuration options via environment variables
  • OWASP security compliance - Input validation best practices
  • PSR compliance - PSR-4, PSR-3, PSR-11, PSR-15 compatible
  • Auto-discovery support - Framework integration ready
  • Comprehensive test coverage - Unit, integration, and performance tests

Quick Start

Installation

composer require highperapp/validator

Build Rust Library (Optional)

./build.sh

Basic Usage

use HighPerApp\HighPer\Validator\ValidatorServiceProvider;

// Bootstrap the validator
$provider = new ValidatorServiceProvider();
$validator = $provider->bootstrap();

// Simple validation
$result = $validator->validate('test@example.com', 'required|email');

if ($result->isValid()) {
    echo "Valid email!";
} else {
    print_r($result->getErrors());
}

// Multi-field validation
$data = [
    'email' => 'user@example.com',
    'age' => 25,
    'website' => 'https://example.com'
];

$rules = [
    'email' => ['required', 'email'],
    'age' => ['required', 'integer', 'min:18', 'max:120'],
    'website' => ['url']
];

$result = $validator->validateMany($data, $rules);

Middleware Usage

use HighPerApp\HighPer\Validator\ValidatorServiceProvider;

// Get middleware instance
$provider = new ValidatorServiceProvider();
$middleware = $provider->getMiddleware();

// Add validation rules for specific routes
$middleware->addRouteRule('POST', '/api/users', [
    'body.name' => 'required|string|max:255',
    'body.email' => 'required|email|unique:users',
    'body.age' => 'required|integer|min:18|max:120'
]);

// Use in PSR-15 compatible middleware stack
$middlewareStack = [
    $middleware,
    // ... other middleware
];

Fluent Rule Builder

use HighPerApp\HighPer\Validator\RuleBuilder;

$rules = RuleBuilder::create()
    ->required()
    ->email(strict: true)
    ->length(min: 5, max: 255)
    ->getRules();

$result = $validator->validate($email, $rules);

Async Validation

// Large dataset validation with automatic parallelization
$result = $validator->validateAsync($largeDataset, $rules);

Engine Configuration

Environment Variables

# Engine preferences
VALIDATOR_PREFERRED_ENGINE=rust_ffi
VALIDATOR_RUST_FFI_ENABLED=true
VALIDATOR_AMPHP_ENABLED=true
VALIDATOR_PURE_PHP_ENABLED=true

# Performance tuning
VALIDATOR_ASYNC_THRESHOLD=50
VALIDATOR_PARALLEL_WORKERS=4

# Validation settings
VALIDATOR_EMAIL_STRICT=true
VALIDATOR_URL_REQUIRE_TLD=true

# Debug settings
VALIDATOR_DEBUG=false
VALIDATOR_LOG_LEVEL=info

Manual Configuration

$config = [
    'engines' => [
        'rust_ffi' => ['enabled' => true],
        'amphp' => ['enabled' => true, 'workers' => 4],
        'pure_php' => ['enabled' => true],
    ],
    'preferred_engine' => 'rust_ffi',
    'performance' => [
        'async_threshold' => 50,
        'parallel_workers' => 4,
    ],
];

$provider = new ValidatorServiceProvider(config: $config);

Available Validation Rules

Basic Types

  • required - Field must be present and not empty
  • optional - Field is optional
  • nullable - Field can be null
  • string - Must be a string
  • integer - Must be an integer
  • float - Must be a float
  • numeric - Must be numeric
  • boolean - Must be a boolean
  • array - Must be an array

String Validation

  • email - Valid email address
  • email:strict - Strict email validation
  • url - Valid URL
  • url:require_tld - URL with TLD requirement
  • regex:/pattern/ - Custom regex pattern
  • length:min,max - String length validation
  • min:value - Minimum length/value
  • max:value - Maximum length/value
  • between:min,max - Value between min and max

Lists and Choices

  • in:value1,value2,value3 - Value must be in list
  • not_in:value1,value2 - Value must not be in list

Dates and Format

  • date - Valid date (Y-m-d format)
  • date:Y-m-d H:i:s - Custom date format
  • json - Valid JSON
  • json:max_depth=512 - JSON with depth limit

Network and Identifiers

  • ip - Valid IP address (IPv4 or IPv6)
  • ip:4 - IPv4 only
  • ip:6 - IPv6 only
  • uuid - Valid UUID
  • uuid:4 - UUID version 4
  • phone - Valid phone number
  • phone:country=US - Country-specific phone

Financial

  • credit_card - Valid credit card number (Luhn algorithm)

Engine Information

Rust FFI Engine (Performance Level 3)

  • Fastest - Native Rust implementation
  • Parallel processing - Automatic batch optimization
  • Advanced validation - Complex regex and format checking
  • Requirements - FFI extension, compiled Rust library

AMPHP Engine (Performance Level 2)

  • amphp/parallel - AMPHP-based parallel processing
  • Worker pools - Configurable worker management
  • Good performance - Balanced speed and compatibility
  • Requirements - AMPHP packages, pcntl extension

Pure PHP Engine (Performance Level 1)

  • Universal compatibility - Works everywhere
  • No dependencies - Only standard PHP functions
  • Reliable fallback - Always available
  • Full featured - All validation rules supported

Framework Integration

Laravel

// In a service provider
public function register()
{
    $this->app->singleton(ValidatorInterface::class, function ($app) {
        $provider = new ValidatorServiceProvider();
        return $provider->bootstrap();
    });
}

Symfony

# services.yaml
services:
    HighPerApp\HighPer\Validator\Contracts\ValidatorInterface:
        factory: ['@HighPerApp\HighPer\Validator\ValidatorServiceProvider', 'bootstrap']
    
    HighPerApp\HighPer\Validator\ValidatorServiceProvider: ~

PSR-11 Container

$container->set(ValidatorInterface::class, function() {
    $provider = new ValidatorServiceProvider();
    return $provider->bootstrap();
});

Performance Benchmarks

Engine Operations/sec Use Case
Rust FFI ~50,000+ High-throughput APIs
AMPHP ~15,000+ Moderate async workloads
Pure PHP ~5,000+ Standard applications

Build Requirements

Rust Library

  • Rust 1.70+
  • Cargo
  • FFI-enabled PHP 8.1+

PHP Requirements

  • PHP 8.1+
  • Composer
  • Optional: AMPHP packages for parallel engine

Development

Building from Source

# Full build with tests
./build.sh --test

# Debug build with verbose output
./build.sh -t debug -v

# Clean rebuild
./build.sh -c -f

# PHP setup only (skip Rust)
./build.sh --php-only

Running Tests

# All tests
./build.sh --test

# Rust tests only
cd rust && cargo test

# PHP tests (if PHPUnit available)
phpunit

Security

This library follows OWASP validation guidelines:

  • Input length limits
  • Regex timeout protection
  • Error message sanitization
  • No code execution in validation rules
  • Secure default configurations

License

MIT License - see LICENSE file

Contributing

  1. Fork the repository
  2. Create feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit pull request

Support

  • GitHub Issues: Report bugs and feature requests
  • Documentation: See docs/ directory
  • Examples: See examples/ directory