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

symfony/polyfill-php85

Symfony Polyfill for PHP 8.5 features on older runtimes. Adds get_error_handler/get_exception_handler, NoDiscard attribute, array_first/array_last, DelayedTargetValidation, Filter exceptions, and locale_is_right_to_left. MIT licensed.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**:
   Update the package via Composer in your Laravel project:
   ```bash
   composer require symfony/polyfill-php85:^1.38.0

No additional configuration is required—it remains a drop-in polyfill.

  1. First Use Case: Replace legacy array operations with PHP 8.5’s array_first and array_last:

    // Before (PHP < 8.5)
    $firstItem = array_slice($array, 0, 1)[0] ?? null;
    
    // After (with polyfill)
    $firstItem = array_first($array) ?? null;
    
  2. Verify Compatibility: Check your PHP version with:

    php -r "echo PHP_VERSION;"
    

    Ensure it’s PHP 7.4–8.4 (the target range for this polyfill). Note: This release fixes a bug related to PCRE < 10.44, which may affect grapheme cluster splitting in edge cases (e.g., multibyte strings).


Implementation Patterns

Usage Patterns

  1. Array Operations: Replace manual array slicing with array_first/array_last for cleaner code:

    // Find first matching item in a collection
    $user = array_first($users, fn($u) => $u['active']);
    

    Note: Ensure your PCRE version is ≥ 10.44 if working with multibyte strings (e.g., emojis, CJK characters).

  2. Attribute-Based Features: Use #[NoDiscard] to enforce return value usage (PHP 8.5+ attribute):

    #[NoDiscard]
    public function getUserData(): array {
        return $this->user->toArray();
    }
    

    Note: Requires PHP 8.0+ for attributes.

  3. Error/Exception Handling: Access global handlers dynamically:

    $handler = get_error_handler();
    $exceptionHandler = get_exception_handler();
    
  4. Filter Validation: Enable strict filter validation with exceptions:

    $value = filter_var($input, FILTER_VALIDATE_EMAIL);
    if ($value === false) {
        throw new Filter\FilterException('Invalid email');
    }
    

Workflows

  1. Gradual Adoption:

    • Start with non-breaking changes (array_first, locale_is_right_to_left).
    • Introduce attributes (NoDiscard, DelayedTargetValidation) in new code only.
    • Avoid retrofitting legacy methods with #[NoDiscard] to minimize disruption.
  2. Testing Strategy:

    • Test polyfilled functions across supported PHP versions (7.4–8.4).
    • Add tests for multibyte strings if using grapheme cluster functions (e.g., array_first with emojis):
      $emojis = ['😀', '😃', '😄'];
      $firstEmoji = array_first($emojis); // Should return '😀'
      $this->assertEquals('😀', $firstEmoji);
      
    • Use PHPUnit to validate NoDiscard behavior:
      $this->expectException(NoReturnInVoidContext::class);
      $this->getUserData(); // Should trigger warning if return value is discarded
      
  3. Laravel Integration:

    • Collections: Use array_first with Laravel’s Collection methods:
      $firstActive = $users->firstWhere('active', true);
      // Equivalent to: array_first($users->toArray(), fn($u) => $u['active'])
      
    • Validation: Replace custom filter logic with FilterException:
      use Symfony\Component\Validator\Constraints\Filter;
      $validator = Validator::make(['email' => $input], [
          'email' => [new Filter(['filter' => FILTER_VALIDATE_EMAIL])]
      ]);
      

Integration Tips

  1. Composer Scripts: Add a script to check for unused polyfills post-upgrade:

    {
      "scripts": {
        "post-upgrade:check": "grep -r \"symfony/polyfill-php85\" app/ || echo \"Polyfill found—remove after PHP 8.5 upgrade\""
      }
    }
    
  2. IDE Support: Add PHPDoc stubs for better autocompletion (e.g., in stubs/php85.php):

    /** @return mixed */
    function array_first(array $array, ?callable $callback = null, mixed $default = null): mixed {}
    
  3. CI/CD: Test polyfills on all supported PHP versions in your CI pipeline:

    # .github/workflows/test.yml
    jobs:
      test:
        strategy:
          matrix:
            php: [7.4, 8.0, 8.1, 8.2, 8.3, 8.4]
        steps:
          - uses: actions/checkout@v4
          - uses: shivammathur/setup-php@v2
            with:
              php-version: ${{ matrix.php }}
          - run: composer install
          - run: phpunit
    

    Note: Add a step to verify PCRE version if multibyte strings are critical:

    - run: php -r "echo preg_version();" | grep -q "10.44" || exit 1
    

Gotchas and Tips

Pitfalls

  1. False Positives with NoDiscard:

    • The polyfill may not trigger warnings in all IDEs or static analyzers (e.g., PHPStan).
    • Fix: Configure PHPStan to recognize NoDiscard:
      # phpstan.neon
      parameters:
        level: 8
        checkReturnTypeInNonVoidFunctions: true
        checkReturnTypeInVoidFunctions: true
      
  2. Attribute System Requirements:

    • NoDiscard and DelayedTargetValidation require PHP 8.0+ (for attributes).
    • Fix: Add a runtime check:
      if (version_compare(PHP_VERSION, '8.0.0') < 0) {
          throw new RuntimeException('PHP 8.0+ required for attributes');
      }
      
  3. locale_is_right_to_left Extension Dependency:

    • The polyfill won’t register if the intl extension is missing.
    • Fix: Check for extension availability:
      if (!extension_loaded('intl')) {
          throw new RuntimeException('Intl extension required for locale_is_right_to_left');
      }
      
  4. Performance Overhead:

    • Polyfills add indirect function calls. Benchmark critical paths:
      php -d memory_limit=-1 bench.php  # Compare native vs. polyfilled `array_first`
      
  5. Deprecation Risk:

    • Symfony’s polyfills may lag behind PHP 8.5 updates.
    • Fix: Monitor Symfony’s polyfill roadmap and pin versions:
      "symfony/polyfill-php85": "^1.38.0"
      
  6. PCRE Version Bug (v1.38.0):

    • Grapheme cluster splitting (e.g., emojis, multibyte strings) may fail on PCRE < 10.44.
    • Fix:
      • Upgrade PCRE if possible (pecl install pcre-10.44).
      • Fallback: Avoid polyfilled functions for multibyte strings or use native PHP 8.5+.
      • Test with:
        if (version_compare(preg_version(), '10.44') < 0) {
            throw new RuntimeException('PCRE 10.44+ required for grapheme cluster support');
        }
        

Debugging Tips

  1. Verify Polyfill Registration: Check if functions are loaded:

    var_dump(function_exists('array_first')); // Should return true
    
  2. Attribute Reflection Issues: If #[NoDiscard] doesn’t work, ensure:

    • PHP version ≥ 8.0.
    • No typos in the attribute name (case-sensitive).
    • The class uses #[Attribute] (PHP 8.1+ syntax).
  3. FilterException Edge Cases:

    • FilterFailedException may not bubble up in all contexts.
    • Fix: Wrap filter calls in try-catch:
      try {
          $value = filter_var($input, FILTER_VALIDATE_EMAIL);
          if ($value === false) {
              throw new Filter\FilterException('Invalid input');
          }
      } catch (Filter\FilterException $e) {
          // Handle
      }
      
  4. **Locale

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