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:

    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., app/Http/Requests/):

    use Symfony\Polyfill\Php81\Php81;
    
    public function rules()
    {
        return [
            'data' => ['required', function ($attribute, $value, $fail) {
                if (!Php81\array_is_list($value)) {
                    $fail('The '.$attribute.' must be a sequential array.');
                }
            }],
        ];
    }
    
  3. Where to Look First:

    • Laravel Validation: Replace array_keys($array) === range(0, count($array) - 1) with Php81\array_is_list($array).
    • Domain Models: Use enum_exists() to check for custom enums (e.g., PaymentStatus::class).
    • Legacy Code: Polyfill MYSQLI_REFRESH_REPLICA or CURLStringFile in database/HTTP layers.

Implementation Patterns

Usage Patterns

  1. Validation Layer:

    • Pattern: Replace manual array checks in FormRequest or Validator classes.
    • Example:
      // Before
      if (!is_array($data) || array_keys($data) !== range(0, count($data) - 1)) {
          return false;
      }
      
      // After
      return Php81\array_is_list($data);
      
  2. Domain-Driven Design (DDD):

    • Pattern: Use enum_exists() to validate domain enums before PHP 8.1 upgrade.
    • Example:
      if (Php81\enum_exists('App\Enums\UserRole')) {
          $role = new UserRole('ADMIN');
      }
      
  3. HTTP/File Uploads:

    • Pattern: Use CURLStringFile for file uploads in legacy Laravel branches.
    • Example:
      $curlFile = new \Symfony\Polyfill\Php81\Php81\CURLStringFile(
          file_get_contents('/path/to/file'),
          'image/png',
          'filename.png'
      );
      curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
      curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => $curlFile]);
      
  4. Deprecation Prep:

    • Pattern: Annotate internal methods with @return void and ReturnTypeWillChange to prepare for PHP 8.1+.
    • Example:
      /**
       * @return void
       * @deprecated Use new method instead
       */
      public function legacyMethod()
      {
          # ReturnTypeWillChange annotation (handled by polyfill)
          return 'string'; // Will be void in PHP 8.1+
      }
      

Workflows

  1. Incremental Adoption:

    • Start with non-critical paths (e.g., validation, logging) before applying to core logic.
    • Use feature flags to toggle polyfill usage during testing.
  2. Testing Strategy:

    • Unit Tests: Mock polyfilled functions to test edge cases:
      $this->partialMock(Php81::class, ['array_is_list'])
           ->method('array_is_list')
           ->willReturn(false);
      
    • Integration Tests: Verify polyfilled features work in Laravel contexts (e.g., Eloquent enums).
  3. Performance Profiling:

    • Benchmark polyfilled functions in high-traffic routes using Laravel Forge or Blackfire.
    • Example: Compare Php81\array_is_list() vs. native array_is_list() in PHP 8.1+.

Integration Tips

  1. Laravel Service Providers:

    • Register polyfilled constants (e.g., MYSQLI_REFRESH_REPLICA) in AppServiceProvider:
      public function boot()
      {
          define('MYSQLI_REFRESH_REPLICA', \Symfony\Polyfill\Php81\Php81\MYSQLI_REFRESH_REPLICA);
      }
      
  2. Custom Helpers:

    • Create a helper trait for frequent polyfill usage:
      trait UsesPhp81Polyfills
      {
          protected function isList(array $array): bool
          {
              return \Symfony\Polyfill\Php81\Php81\array_is_list($array);
          }
      }
      
  3. CI/CD Pipeline:

    • Add a compatibility check in GitHub Actions to ensure polyfills work across PHP 7.4–8.0:
      - name: Test with Polyfill
        run: composer require symfony/polyfill-php81 && php artisan test
      
  4. Documentation:

    • Use PHPDoc annotations to clarify polyfill usage:
      /**
       * @param array $array Must be a sequential list (checked via Php81\array_is_list)
       */
      public function process(array $array): void
      

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatches:

    • Issue: Using CURLStringFile on PHP <7.4 will throw errors (polyfill checks runtime PHP version).
    • Fix: Ensure composer.json enforces PHP ≥7.4:
      "config": {
          "platform": {
              "php": "7.4"
          }
      }
      
  2. Enum Behavior Differences:

    • Issue: enum_exists() may return true for invalid enums in polyfilled environments.
    • Fix: Validate enums manually:
      if (Php81\enum_exists('App\Enums\Status') && class_exists('App\Enums\Status')) {
          $enum = new Status();
      }
      
  3. Performance Overhead:

    • Issue: Polyfilled functions may be 2–5x slower than native PHP 8.1+ implementations.
    • Fix: Benchmark critical paths and consider custom implementations for hot code:
      // Custom array_is_list (faster than polyfill for some cases)
      function is_list(array $array): bool {
          return array_keys($array) === range(0, count($array) - 1);
      }
      
  4. Laravel 10+ Conflicts:

    • Issue: Laravel 10+ assumes PHP 8.1+ and may conflict with polyfills.
    • Fix: Remove polyfill when upgrading:
      composer remove symfony/polyfill-php81
      
  5. ReturnTypeWillChange Misuse:

    • Issue: Annotating external methods may cause type errors in PHP 8.1+.
    • Fix: Restrict usage to internal/private methods:
      private function internalMethod()
      {
          // ReturnTypeWillChange (safe for internal use)
          return 'string'; // Will be void in PHP 8.1+
      }
      

Debugging

  1. Polyfill Not Loading:

    • Symptom: Class 'Symfony\Polyfill\Php81\Php81' not found.
    • Debug:
      composer dump-autoload
      
    • Fix: Ensure composer.json includes the package and run composer install --no-dev.
  2. Method Not Found Errors:

    • Symptom: Call to undefined method Php81::array_is_list().
    • Debug: Verify the correct namespace:
      use Symfony\Polyfill\Php81\Php81; // Correct
      // vs.
      use Symfony\Polyfill\Php81; // Incorrect (missing \Php81)
      
  3. Runtime PHP Version Checks:

    • Symptom: CURLStringFile fails with "PHP version not supported".
    • Debug: Check runtime PHP version:
      var_dump(PHP_VERSION_ID >= 70400); // Must be true
      

Tips

  1. Alias for Cleaner Code:

    • Add a global alias in config/app.php:
      'aliases' => [
          'Php81' => Symfony\Polyfill\Php81\Php81::class,
      ],
      
    • Usage:
      if (Php81::array_is_list($data)) { ... }
      
  2. Laravel Artisan Commands:

    • Use polyfills in custom commands for PHP 7.4–8.0 compatibility:
      use Symfony\Polyfill\Php8
      
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony