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 Php73 Laravel Package

symfony/polyfill-php73

Symfony Polyfill for PHP 7.3: provides missing core features on older PHP versions, including array_key_first/last, hrtime, is_countable, and JsonException. Part of Symfony’s polyfill set for forward-compatible apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/polyfill-php73
    
    • No additional configuration is required. The polyfills are autoloaded conditionally based on the PHP version.
  2. First Use Case: Replace legacy array traversal with array_key_first in a Laravel controller or service:

    // Before (PHP <7.3)
    $key = array_search('target', $array);
    $firstKey = reset(array_keys($array));
    
    // After (works on PHP ≥7.2 with polyfill)
    $firstKey = array_key_first($array);
    
  3. Verify Compatibility:

    • Test on PHP 7.2 or lower to ensure polyfills activate.
    • Confirm native behavior on PHP 7.3+ (polyfills are ignored, no runtime overhead).

Implementation Patterns

Usage Patterns

  1. Array Traversal:

    • Replace manual key-finding logic with array_key_first/array_key_last:
      // Eloquent example: Find first key in a collection
      $firstId = array_key_first($user->roles->toArray());
      
  2. JSON Error Handling:

    • Use JsonException for robust JSON parsing (e.g., API responses):
      try {
          $data = json_decode($response, false, 512, JSON_THROW_ON_ERROR);
      } catch (JsonException $e) {
          Log::error('Invalid JSON: ' . $e->getMessage());
          return response()->json(['error' => 'Invalid data'], 400);
      }
      
  3. High-Resolution Timing:

    • Benchmark performance with hrtime (e.g., middleware execution):
      $start = hrtime(true);
      // ... code to measure ...
      $duration = hrtime(true) - $start;
      Log::debug("Execution time: {$duration} nanoseconds");
      
  4. Countable Checks:

    • Replace is_array + count with is_countable:
      if (is_countable($items)) {
          $count = count($items);
      }
      

Workflows

  1. Phased Migration:

    • Adopt polyfills now, remove them post-PHP upgrade (no refactoring needed):
      # Add to composer.json
      composer require symfony/polyfill-php73
      
      # Remove after PHP 7.3+ upgrade
      composer remove symfony/polyfill-php73
      
  2. Laravel Package Development:

    • Target older PHP versions while using modern features internally:
      // Package code (works on PHP 7.2+ with polyfill)
      public function getFirstKey(array $array): ?string
      {
          return array_key_first($array);
      }
      
  3. Cross-Environment Consistency:

    • Standardize behavior across dev/staging/prod (e.g., local PHP 8.1, prod PHP 7.2):
      // Works identically on all environments
      $key = array_key_first($config['settings']);
      

Integration Tips

  • Leverage Laravel’s Collections: Combine with Laravel’s collection methods for cleaner syntax:

    $firstKey = $collection->keys()->first();
    // Or with polyfill:
    $firstKey = array_key_first($collection->toArray());
    
  • CI/CD Enforcement: Add PHP version checks to prevent accidental deployment on unsupported versions:

    # GitHub Actions example
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: shivammathur/setup-php@v2
            with:
              php-version: '7.2'
    
  • Static Analysis: Use PHPStan/Psalm to detect unused polyfills (indicating no runtime impact):

    vendor/bin/phpstan analyse --level=5
    

Gotchas and Tips

Pitfalls

  1. Redundant Polyfills:

    • Laravel may already include symfony/polyfill via dependencies. Check:
      composer show symfony/polyfill
      
    • If present, this package may be unnecessary (but harmless).
  2. PHP Version Mismatch:

    • Polyfills activate on PHP <7.3. Test explicitly on target versions:
      docker run --rm -it php:7.2-cli composer show symfony/polyfill-php73
      
  3. Custom Polyfill Conflicts:

    • Avoid redefining polyfilled functions (e.g., array_key_first) elsewhere in the codebase. Audit with:
      grep -r "array_key_first" app/
      
  4. Performance Overhead:

    • Polyfills add minimal runtime cost (lazy-loaded, <0.1ms). Benchmark critical paths:
      $start = microtime(true);
      array_key_first($largeArray);
      $time = microtime(true) - $start;
      

Debugging

  1. Verify Polyfill Activation: Check if polyfills are loaded:

    if (function_exists('array_key_first')) {
        echo "Polyfill active (PHP <7.3)";
    }
    
  2. JSON Exception Handling: Ensure JSON_THROW_ON_ERROR is supported (PHP 7.3+). Polyfill provides compatibility:

    json_decode($json, false, 512, JSON_THROW_ON_ERROR); // Works with polyfill
    
  3. hrtime Precision: Note hrtime returns nanoseconds (float). Convert to milliseconds for readability:

    $durationMs = (hrtime(true) - $start) / 1_000_000;
    

Tips

  1. Version Pinning: Lock to a specific version to avoid surprises:

    "symfony/polyfill-php73": "1.37.0"
    
  2. Laravel-Specific: Combine with Laravel’s Str::of() or collect() for cleaner syntax:

    $firstKey = Str::of($array)->keys()->first();
    
  3. Future-Proofing: Use feature detection to handle both polyfilled and native implementations:

    if (defined('JSON_THROW_ON_ERROR')) {
        json_decode($json, false, 512, JSON_THROW_ON_ERROR);
    } else {
        $data = json_decode($json);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new JsonException(json_last_error_msg());
        }
    }
    
  4. Testing: Mock polyfills in tests to avoid environment dependencies:

    // tests/TestCase.php
    protected function setUp(): void
    {
        if (!function_exists('array_key_first')) {
            function array_key_first(array $array): ?string
            {
                return key($array);
            }
        }
    }
    
  5. Removal Post-Upgrade: After upgrading PHP, remove the package and update tests:

    composer remove symfony/polyfill-php73
    # Update tests to remove mocks
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope