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

Polyfill Php84 Laravel Package

symfony/polyfill-php84

Symfony Polyfill for PHP 8.4 features, enabling newer core functions and APIs on older runtimes. Includes array_find/any/all, bcdivmod, Deprecated attribute, fpow, grapheme_str_split, mb_* trim/ucfirst/lcfirst, PDO subclasses, and ReflectionConstant.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package to your composer.json:

    composer require symfony/polyfill-php84
    

    Laravel’s autoloader will handle the rest—no manual require needed.

  2. First Use Case: Replace legacy array operations with PHP 8.4+ functions. Example:

    // Before (Laravel 9.x/10.x on PHP ≤8.3)
    $admin = collect($users)->first(fn($user) => $user['role'] === 'admin');
    
    // After (using polyfill)
    $admin = array_find($users, fn($user) => $user['role'] === 'admin');
    

    Verify: Check php -r "echo PHP_VERSION;" to confirm your environment still reports ≤8.3.

  3. Where to Look First:

    • Array Functions: array_find, array_find_key (replace collect()->first()).
    • Multibyte Strings: mb_trim, mb_ucfirst (fixes for null inputs in Laravel validation).
    • Deprecation: Use #[Deprecated] in custom classes to align with Laravel’s deprecation practices.

Implementation Patterns

Usage Patterns

  1. Array Operations:

    • Replace collect()->first():
      // Laravel Collection
      $user = User::where('role', 'admin')->first();
      
      // Polyfill alternative
      $user = array_find(User::all()->toArray(), fn($u) => $u['role'] === 'admin');
      
    • Filtering with array_all:
      $allActive = array_all($users, fn($u) => $u['active']);
      
  2. Multibyte String Handling:

    • Trim Unicode Whitespace:
      $cleanInput = mb_trim($request->input('name')); // Handles emojis, CJK
      
    • Case Conversion:
      $title = mb_ucfirst($request->input('title')); // Correct for non-ASCII
      
  3. Deprecation Management:

    • Mark Legacy APIs:
      #[Deprecated('Use App\Services\V2\LegacyService instead')]
      class LegacyService { ... }
      
    • Laravel Integration: Combine with Illuminate\Support\Facades\DeprecatesFunctions for unified warnings.
  4. Math/Precision:

    • Financial Calculations:
      $result = bcdivmod('10.5', '3', 4); // '3.5000' (PHP 8.4+)
      
    • Scientific Data:
      $power = fpow(2, -3); // 0.125 (handles negative exponents)
      
  5. PDO and cURL:

    • SSL Verification:
      $pdo->setAttribute(PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT, true);
      
    • HTTP/3 Support:
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_3);
      

Workflows

  1. Gradual Migration:

    • Use polyfills in new features while keeping legacy code in PHP ≤8.3.
    • Example: Add array_find to a new admin panel before upgrading the entire app.
  2. Localization Pipelines:

    • Replace Str::of()->trim() with mb_trim() in multilingual validation rules:
      'name' => ['required', fn($attr, $value) => mb_strlen(mb_trim($value)) > 2],
      
  3. Testing Strategy:

    • Unit Tests: Mock polyfilled functions to test edge cases (e.g., array_find on empty arrays).
    • Integration Tests: Verify mb_trim in form requests with Unicode input.
    • Benchmark: Compare array_find vs. collect()->first() in high-load routes.
  4. CI/CD Integration:

    • Add a PHP version check in GitHub Actions:
      - name: Check PHP Version
        run: |
          if [ $(php -r 'echo PHP_VERSION;') != "8.4.0" ]; then
            composer require symfony/polyfill-php84
          fi
      

Integration Tips

  • Laravel Collections: Polyfills complement (not replace) Laravel’s collections. Use array_find for simple arrays, but prefer collect()->where()->first() for complex queries.

  • Service Providers: Register polyfill-aware bindings:

    public function register()
    {
        $this->app->bind('array_finder', fn() => new class {
            public function find(array $items, callable $callback) {
                return array_find($items, $callback);
            }
        });
    }
    
  • Blade Templates: Use @php directives for polyfill-heavy logic:

    @php
        $highlighted = array_find($posts, fn($p) => $p['featured']);
    @endphp
    
  • Database Seeds: Leverage array_all for validation:

    $validUsers = array_all($users, fn($u) => filled($u['email']));
    

Gotchas and Tips

Pitfalls

  1. PCRE Version Mismatch:

    • Issue: grapheme_str_split fails on PCRE <10.44 (common in shared hosting).
    • Fix: Add a runtime check:
      if (version_compare(PCRE_VERSION, '10.44') < 0) {
          throw new RuntimeException('Upgrade PCRE for grapheme_str_split support.');
      }
      
    • Workaround: Use preg_split('/\X/u', $string) as a fallback.
  2. null Handling in mb_* Functions:

    • Issue: mb_trim(null) throws TypeError in PHP ≤8.3 (fixed in v1.38.0+).
    • Fix: Always sanitize input:
      $clean = mb_trim($value ?? '');
      
  3. Array Function Edge Cases:

    • Issue: array_find may return false (not null) for empty arrays.
    • Fix: Normalize results:
      $result = array_find($items, $callback) ?: null;
      
  4. PDO Driver Subclasses:

    • Issue: Polyfill may conflict with custom PDO drivers.
    • Fix: Test with PDO::getAvailableDrivers() and PDO::getAttribute(PDO::ATTR_DRIVER_NAME).
  5. Deprecated Attribute:

    • Issue: #[Deprecated] requires PHP 8.0+ (polyfill works on PHP 7.2+ but may not trigger warnings).
    • Fix: Combine with Laravel’s DeprecatesFunctions:
      use Illuminate\Support\Facades\DeprecatesFunctions;
      DeprecatesFunctions::add('App\LegacyClass', '1.0', 'Use App\NewClass instead');
      
  6. Performance Overhead:

    • Issue: Polyfills add ~5–10% overhead to array_find/array_all in microbenchmarks.
    • Fix: Cache results or use native functions in PHP 8.4+:
      if (PHP_VERSION_ID >= 80400) {
          return array_find($items, $callback);
      }
      

Debugging

  1. Verify Polyfill Loading:

    composer show symfony/polyfill-php84
    

    Ensure it’s listed under require.

  2. Check for Overrides:

    • If array_find behaves unexpectedly, search for custom extensions or userland overrides:
      grep -r "array_find" app/
      
  3. PCRE Debugging:

    • Log PCRE version in bootstrap/app.php:
      \Log::debug('PCRE Version:', PCRE_VERSION);
      
  4. Deprecation Warnings:

    • Ensure #[Deprecated] triggers warnings by checking error_reporting(E_ALL).

Config Quirks

  1. Autoloading:

    • Laravel’s composer.json autoloads polyfills automatically. Avoid manual require statements.
  2. Environment-Specific Loading:

    • Load polyfills conditionally in bootstrap/app.php:
      if (PHP_VERSION_ID < 80400) {
          require __DIR__.'/../vendor/symfony/polyfill-php84/bootstrap.php';
      }
      
  3. Composer Scripts:

    • Add a post-install script to warn about PHP version
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle