Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Random Polyfill Laravel Package

arokettu/random-polyfill

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Polyfill for ext-random: The package provides a 1:1 API compatibility with PHP 8.2’s Random\ namespace, making it a drop-in replacement for applications targeting PHP 8.2 but constrained to older versions (7.1–8.1). This aligns perfectly with Laravel’s dependency injection and service container patterns, where randomness is often abstracted (e.g., via Illuminate\Support\Facades\Str or custom services).
  • Engine-Based Design: The modular Random\Engine interfaces (Secure, Mt19937, PcgOneseq128XslRr64, etc.) enable strategic selection of PRNGs based on use case (e.g., Secure for cryptography, Xoshiro256StarStar for performance). Laravel’s config-driven services (e.g., config/random.php) can easily bind these engines.
  • Serialization Compatibility: Critical for stateful services (e.g., caching random seeds, distributed systems). The polyfill ensures Randomizer objects serialize/unserialize identically to PHP 8.2, enabling Laravel’s session, cache, or queue systems to leverage randomness seamlessly.
  • GMP Dependency: While optional, the GMP extension is strongly recommended for cryptographic operations. Laravel’s environment-aware configuration (e.g., .env) can gate this requirement (e.g., RANDOM_POLYFILL_USE_GMP=true).

Integration Feasibility

  • Laravel Service Provider: The package can be bootstrapped via a Laravel service provider to register:
    • A facade (e.g., Random::getInt()) mirroring PHP 8.2’s API.
    • Bindings for Random\Randomizer and engine interfaces in the container.
    • Helpers for common use cases (e.g., Str::random() fallback, cryptographic token generation).
  • Composer Integration: Zero friction—install via composer require arokettu/random-polyfill. Laravel’s autoloader handles the rest.
  • PHP 8.2 Fallback: The package auto-detects PHP 8.2+ and delegates to the native ext-random, requiring no code changes during upgrades. This is ideal for gradual migration strategies.
  • Laravel-Specific Hooks:
    • Event Listeners: Trigger random.engine.selected events when an engine is swapped (e.g., for logging/auditing).
    • Middleware: Inject randomness into requests (e.g., X-CSRF-Token generation).
    • Artisan Commands: Add php artisan random:generate for CLI-based random data creation.

Technical Risk

Risk Area Mitigation Strategy Severity
Performance Overhead Benchmark against mt_rand/rand in Laravel’s environment. The polyfill’s engine optimizations (e.g., 32-bit/64-bit fixes) reduce this risk, but cryptographic engines (Secure) will be slower than native ext-random. Medium
API Drift Monitor PHP 8.2+ releases for breaking changes. The package’s test suite (ported from PHP’s engine) ensures compatibility. Laravel’s semver constraints can pin the polyfill version. Low
GMP Dependency Laravel’s .env can enforce GMP presence for security-sensitive features. Alternatively, use Random\Engine\Mt19937 (non-crypto) where GMP isn’t required. Medium
Serialization Issues Test with Laravel’s session, cache, and queue systems. The polyfill’s PHP 7.4+ serialization compatibility covers Laravel’s supported PHP versions (8.0+). Low
Thread Safety The polyfill is thread-safe (like ext-random), but Laravel’s request lifecycle (single-threaded) mitigates most risks. For queues/workers, ensure engines are stateless or use clone() carefully. Low
License Compliance The 3-Clause BSD license is Laravel-compatible. No conflicts with Laravel’s MIT license. None

Key Questions

  1. Randomness Use Cases:
    • What specific features of ext-random are critical for Laravel’s roadmap? (e.g., Secure for passwords, PcgOneseq128XslRr64 for performance?)
    • Are there legacy Laravel packages (e.g., laravel/framework <8.0) using rand()/mt_rand that need replacement?
  2. Performance SLAs:
    • What’s the acceptable overhead for random operations? (e.g., 10% slower than mt_rand may be tolerable for non-crypto uses.)
    • Should non-critical randomness (e.g., UI personalization) use faster engines (e.g., Mt19937) while crypto uses Secure?
  3. Migration Strategy:
    • Should Laravel default to the polyfill in PHP <8.2 and auto-switch to native ext-random in PHP 8.2+?
    • How to deprecate Str::random()’s fallback to openssl_random_pseudo_bytes() in favor of this polyfill?
  4. Testing:
    • Are there existing Laravel tests for randomness (e.g., tests/Unit/Str.php) that need updating?
    • Should fuzz testing be added to verify engine outputs match PHP 8.2’s ext-random?
  5. Security:
    • How to audit the Secure engine’s cryptographic guarantees in PHP <8.2?
    • Should Laravel force GMP for Secure engine in production?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Bind Random\Randomizer and engines as singletons/lazy services.
    • Facades: Create Random::getInt(), Random::shuffleArray() facades for backward compatibility.
    • Helpers: Extend Str::random() to use the polyfill (e.g., Str::random(32, 'Secure')).
    • Artisan: Add random:generate command for CLI random data.
  • PHP Extensions:
    • GMP: Required for cryptographic operations. Laravel’s .env can enforce this (e.g., RANDOM_POLYFILL_REQUIRE_GMP=true).
    • OpenSSL: Fallback for Secure engine if GMP is unavailable (but less performant).
  • Database:
    • Use Randomizer::getBytes() for UUIDs, tokens, or encrypted fields (e.g., DB::raw('(SELECT HEX(RANDOM_BYTES(16)))') alternative).
  • Queue/Jobs:
    • Seed Randomizer objects in jobs for deterministic retries or distributed randomness.

Migration Path

Phase Action Laravel Integration
Assessment Audit Laravel codebase for rand(), mt_rand(), openssl_random_pseudo_bytes(). Identify ext-random dependencies (e.g., in packages like laravel/passport). Run `grep -r "rand
Polyfill Adoption Install arokettu/random-polyfill. Register a service provider to bind Random\Randomizer and engines. Create RandomServiceProvider with boot() method to publish config.
API Wrapping Create facades/helpers (e.g., Random::getInt(), Str::random()) to abstract the polyfill. Extend Illuminate\Support\Str or add Random facade.
Testing Verify outputs match PHP 8.2’s ext-random using property-based testing (e.g., phpunit/random-data-provider). Add tests to tests/Unit/Random (if created).
Performance Tuning Benchmark engines (e.g., Mt19937 vs. PcgOneseq128XslRr64). Optimize for Laravel’s use cases (e.g., cache Randomizer instances). Use Laravel\Benchmark package to measure impact.
PHP 8.2 Rollout Update composer.json to drop the polyfill (it auto-falls back to ext-random). Remove polyfill dependency; update config/random.php to use native engines.

Compatibility

  • PHP Versions:
    • Supported:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat