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

symfony/polyfill-php81

Symfony Polyfill for PHP 8.1 features on older runtimes. Adds array_is_list, enum_exists, MYSQLI_REFRESH_REPLICA, ReturnTypeWillChange, and CURLStringFile (PHP 7.4+). Drop-in Composer dependency for wider compatibility.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the polyfill via Composer:

    composer require symfony/polyfill-php81
    

    For development/testing only:

    composer require --dev symfony/polyfill-php81
    
  2. First Use Case: Replace manual array validation with array_is_list in Laravel’s validation logic (e.g., API request payloads):

    use Symfony\Polyfill\Php81\Php81;
    
    $payload = [1, 2, 3];
    if (Php81\array_is_list($payload)) {
        // Process sequential array
    }
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. Validation Layers: Replace custom sequential array checks with array_is_list in Laravel’s FormRequest or API validation:

    public function rules()
    {
        return [
            'data' => ['required', function ($attribute, $value, $fail) {
                if (!Php81\array_is_list($value)) {
                    $fail('The :attribute must be a sequential array.');
                }
            }],
        ];
    }
    
  2. Domain Models with Enums: Use enum_exists and enums in Laravel models (PHP 7.4–8.0):

    use Symfony\Polyfill\Php81\Php81;
    
    if (Php81\enum_exists('App\Models\PaymentStatus')) {
        // Safe to use enums
        $status = PaymentStatus::PENDING;
    }
    
  3. HTTP/File Operations: Leverage CURLStringFile for file uploads in legacy Laravel branches:

    $file = new \Symfony\Polyfill\Php81\Curl\CurlFile('/path/to/file', 'text/plain');
    $response = Http::post('https://api.example.com/upload', [
        'file' => $file,
    ]);
    
  4. Internal Method Refactoring: Annotate methods with @return void using ReturnTypeWillChange during PHP 8.1 migration prep:

    /**
     * @return void
     * @deprecated Use native return type declarations in PHP 8.1+
     */
    public function legacyMethod()
    {
        # ReturnTypeWillChange annotation (handled by polyfill)
    }
    

Workflows

  1. Feature-Flagged Adoption: Wrap polyfill usage in feature flags for gradual rollout:

    if (feature_enabled('php81_polyfills')) {
        if (Php81\array_is_list($data)) { ... }
    } else {
        // Fallback logic
    }
    
  2. Testing Strategy:

    • Unit Tests: Mock polyfilled functions for isolation:
      $this->mock(Php81::class)
           ->shouldReceive('array_is_list')
           ->andReturnTrue();
      
    • Integration Tests: Verify polyfill behavior in Laravel contexts (e.g., Eloquent enums).
  3. Performance Profiling: Benchmark polyfilled functions in critical paths (e.g., API routes) using:

    php -d memory_limit=-1 vendor/bin/phpunit --testdox --filter=PerformanceTest
    

Integration Tips

  1. Laravel Service Providers: Register polyfill-aware services in AppServiceProvider:

    public function boot()
    {
        if (Php81\enum_exists('App\Models\UserRole')) {
            $this->app->bind('role_resolver', UserRoleResolver::class);
        }
    }
    
  2. Custom Validation Rules: Extend Laravel’s validator with polyfill-aware rules:

    Validator::extend('is_sequential_array', function ($attribute, $value, $parameters) {
        return Php81\array_is_list($value);
    });
    
  3. PHPStan/Psalm Integration: Configure static analyzers to recognize polyfilled types:

    # phpstan.neon
    parameters:
        level: 8
        includePhp: true
        polyfillPhp81: true
    

Gotchas and Tips

Pitfalls

  1. False Positives in array_is_list:

    • Polyfill may return true for arrays with null values (e.g., [null, 1, 2]), unlike PHP 8.1’s stricter behavior.
    • Fix: Add explicit checks:
      if (Php81\array_is_list($array) && !in_array(null, $array)) { ... }
      
  2. Enum Behavior Differences:

    • Polyfilled enum_exists may not replicate PHP 8.1’s case-sensitive checks.
    • Fix: Use strtolower for enum names:
      if (Php81\enum_exists(strtolower('App\Models\PaymentStatus'))) { ... }
      
  3. ReturnTypeWillChange Overhead:

    • Annotations may trigger reflection warnings in debug mode.
    • Fix: Disable warnings or use only in non-debug environments.
  4. PHP 8.1+ Conflicts:

    • Installing the polyfill on PHP 8.1+ may cause:
      • Deprecation warnings for polyfilled functions.
      • Unexpected behavior if native functions override polyfills.
    • Fix: Remove the polyfill via:
      composer remove symfony/polyfill-php81
      
  5. Composer Autoload Issues:

    • Polyfill classes may not autoload if composer dump-autoload is skipped.
    • Fix: Run:
      composer dump-autoload --optimize
      

Debugging

  1. Polyfill Not Loading:

    • Verify the namespace:
      var_dump(class_exists('Symfony\Polyfill\Php81\Php81'));
      
    • Fix: Ensure symfony/polyfill-php81 is in composer.json and autoloaded.
  2. Performance Bottlenecks:

    • Use Xdebug to profile polyfilled function calls:
      php -dxdebug.mode=profile -dxdebug.output_dir=/tmp app/Artisan tinker
      
    • Tip: Cache polyfill results for immutable inputs (e.g., request payloads).
  3. Enum Serialization Issues:

    • Polyfilled enums may fail JSON serialization in API responses.
    • Fix: Use custom JSON encoders:
      $encoder = new JsonEncoder();
      $encoder->encode($enumInstance->value);
      

Config Quirks

  1. Laravel Mix/Webpack:

    • Polyfills are PHP-only; no Webpack configuration changes are needed.
  2. Environment-Specific Loading:

    • Load polyfills only in non-PHP 8.1+ environments:
      if (version_compare(PHP_VERSION, '8.1.0', '<')) {
          require __DIR__.'/vendor/autoload.php'; // Ensure polyfill is loaded
      }
      
  3. CI/CD Pipeline:

    • Test polyfill behavior in CI for all supported PHP versions:
      # .github/workflows/tests.yml
      jobs:
        test:
          runs-on: ubuntu-latest
          strategy:
            matrix:
              php: ['7.4', '8.0', '8.1']
          steps:
            - uses: actions/checkout@v2
            - uses: shivammathur/setup-php@v2
              with:
                php-version: ${{ matrix.php }}
            - run: composer install
            - run: php artisan test
      

Extension Points

  1. Custom Polyfill Logic:

    • Override polyfilled functions in a service provider:
      $this->app->singleton('array_is_list', function () {
          return function ($array) {
              // Custom implementation
              return array_keys($array) === range(0, count($array) - 1);
          };
      });
      
  2. Laravel Facade Integration:

    • Create a facade for polyfill functions:
      // app/Facades/Polyfill.php
      namespace App\Facades;
      
      use Illuminate\Support\Facades\Facade;
      use Symfony\Polyfill\Php81\Php81;
      
      class Polyfill extends Facade
      {
          public static function getFacadeAccessor()
          {
              return Php81::class;
          }
      }
      
      Usage:
      if (Polyfill::array_is_list($data)) { ... }
      
  3. **Dynamic Feature

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.
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
anil/file-picker
broqit/fields-ai