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
Requires
- php: ^8.1|^8.2|^8.3|^8.4
- amphp/amp: ^3.0
- amphp/parallel: ^2.0
- psr/container: ^2.0
- psr/log: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^10.0|^11.0
- symfony/var-dumper: ^6.0|^7.0
Suggests
- ext-ffi: For Rust FFI acceleration and maximum validation performance
- ext-igbinary: For faster serialization
- ext-intl: For international validation features
- ext-mbstring: For multibyte string validation
- ext-msgpack: For compact data serialization
- ext-uv: For enhanced async I/O performance
- highperapp/crypto: For enhanced cryptographic validation features
- highperapp/security: For enterprise security validation patterns
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 emptyoptional
- Field is optionalnullable
- Field can be nullstring
- Must be a stringinteger
- Must be an integerfloat
- Must be a floatnumeric
- Must be numericboolean
- Must be a booleanarray
- Must be an array
String Validation
email
- Valid email addressemail:strict
- Strict email validationurl
- Valid URLurl:require_tld
- URL with TLD requirementregex:/pattern/
- Custom regex patternlength:min,max
- String length validationmin:value
- Minimum length/valuemax:value
- Maximum length/valuebetween:min,max
- Value between min and max
Lists and Choices
in:value1,value2,value3
- Value must be in listnot_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 formatjson
- Valid JSONjson:max_depth=512
- JSON with depth limit
Network and Identifiers
ip
- Valid IP address (IPv4 or IPv6)ip:4
- IPv4 onlyip:6
- IPv6 onlyuuid
- Valid UUIDuuid:4
- UUID version 4phone
- Valid phone numberphone: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
- Fork the repository
- Create feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit pull request
Support
- GitHub Issues: Report bugs and feature requests
- Documentation: See docs/ directory
- Examples: See examples/ directory