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:

    composer require symfony/polyfill-php85
    

    Add to composer.json under require or require-dev depending on your needs.

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

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

    "config": {
        "platform": {
            "php": "8.1" // or your current version
        }
    }
    

Where to Look First

  • Polyfill Features: README.md for a list of supported functions/attributes.
  • Laravel Integration: Focus on array_first, array_last, NoDiscard, and FilterException for immediate value.
  • IDE Support: Add PHPDoc stubs if autocompletion is missing:
    /**
     * @return mixed
     */
    function array_first(array $array): mixed { /* ... */ }
    

Implementation Patterns

Usage Patterns

  1. Array Operations:

    // Find first/last item in a collection
    $first = array_first($users->toArray());
    $last = array_last($users->toArray());
    
    // Replace Laravel Collection methods
    $user = $users->first(fn($u) => $u->isActive());
    // vs.
    $user = array_first(array_filter($users->toArray(), fn($u) => $u->isActive()));
    
  2. Attribute-Based Features:

    // Enforce non-discardable return values
    #[NoDiscard]
    public function getCriticalData(): string {
        return $this->data;
    }
    
    // Delayed validation (e.g., for DTOs)
    #[DelayedTargetValidation]
    public function setName(string $name) {
        $this->name = $name;
    }
    
  3. Filter Exception Handling:

    // Throw exceptions on filter failures
    try {
        $cleaned = filter_var($input, FILTER_VALIDATE_EMAIL);
    } catch (FilterException $e) {
        // Handle invalid input
    }
    
  4. Error/Exception Inspection:

    // Debug custom handlers
    $handler = get_exception_handler();
    if ($handler instanceof Closure) {
        // Log or inspect handler logic
    }
    

Workflows

  1. Incremental Modernization:

    • Start with array_first/array_last in non-critical modules (e.g., admin panels).
    • Gradually introduce NoDiscard in new classes to catch bugs early.
    • Use FilterException in validation layers (e.g., FormRequests) before full PHP upgrade.
  2. Laravel-Specific Patterns:

    • Service Providers: Polyfills work out-of-the-box; no registration needed.
    • Migrations: Use array_first to simplify whereIn clauses:
      $ids = array_first($request->input('ids', []));
      User::where('id', $ids)->update(...);
      
    • Testing: Mock polyfilled functions in PHPUnit:
      $this->getMockBuilder('Symfony\Component\Polyfill\Php85\array_first')
           ->disableOriginalConstructor()
           ->getMock();
      
  3. CI/CD Integration:

    • Test polyfill behavior across PHP versions (7.4–8.4) in GitHub Actions:
      jobs:
        test:
          runs-on: ubuntu-latest
          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
      

Integration Tips

  • Laravel Collections: Combine with Collection::toArray() for seamless integration:
    $first = array_first($collection->toArray());
    
  • Validation: Use FilterException in FormRequest validation:
    public function rules(): array {
        return [
            'email' => ['required', 'email:rfc,dns,spoof'],
        ];
    }
    public function withValidator($validator) {
        $validator->after(function ($validator) {
            if ($validator->errors()->any()) {
                throw new FilterException('Validation failed');
            }
        });
    }
    
  • Attributes: Pair with Laravel’s attribute system for consistency:
    use Symfony\Component\Polyfill\Php85\NoDiscard;
    
    #[NoDiscard]
    #[HasFactory]
    class User {
        // ...
    }
    

Gotchas and Tips

Pitfalls

  1. IDE False Positives:

    • Symptom: IDE (PHPStorm/VSCode) shows polyfilled functions as undefined.
    • Fix: Add PHPDoc stubs or configure IDE to include vendor/autoload.php:
      // In a helper file (e.g., `stubs.php`)
      declare(strict_types=1);
      function array_first(array $array): mixed { return null; }
      function array_last(array $array): mixed { return null; }
      
  2. Attribute Reflection Issues:

    • Symptom: NoDiscard or DelayedTargetValidation attributes are ignored.
    • Root Cause: PHP <8.0 lacks attribute reflection. Ensure your Laravel app targets PHP 8.0+.
    • Fix: Add to phpstan.neon:
      parameters:
        attributes:
          knownAttributes:
            - Symfony\Component\Polyfill\Php85\NoDiscard
            - Symfony\Component\Polyfill\Php85\DelayedTargetValidation
      
  3. locale_is_right_to_left Requires intl:

    • Symptom: Function exists but returns false or errors.
    • Fix: Install the intl extension:
      pecl install intl
      
      Or enable in php.ini:
      extension=intl
      
  4. FilterException Changes Error Flow:

    • Symptom: Existing filter_var calls now throw exceptions.
    • Fix: Wrap in try-catch or update validation logic:
      try {
          $cleaned = filter_var($input, FILTER_VALIDATE_EMAIL);
      } catch (FilterException $e) {
          $this->fail('Invalid email format.');
      }
      
  5. Polyfill Removal Post-Upgrade:

    • Symptom: Forgetting to remove the polyfill after upgrading PHP.
    • Fix: Add a composer post-update script:
      "scripts": {
        "post-update": "php -r \"if (file_exists(__DIR__.'/vendor/symfony/polyfill-php85') && version_compare(PHP_VERSION, '8.5.0') >= 0) echo 'WARNING: polyfill-php85 is unused after PHP 8.5 upgrade.\\n';\""
      }
      

Debugging

  1. Verify Polyfill Registration:

    // Check if polyfill is loaded
    if (!function_exists('array_first')) {
        echo 'Polyfill not loaded. Run `composer dump-autoload`.';
    }
    
  2. Attribute Debugging:

    // Inspect attributes at runtime
    $reflection = new ReflectionClass(User::class);
    $attributes = $reflection->getAttributes(NoDiscard::class);
    
  3. Filter Exception Handling:

    // Log filter failures
    set_error_handler(function ($errno, $errstr) {
        if (strpos($errstr, 'filter') !== false) {
            Log::error("Filter error: {$errstr}");
        }
    });
    

Config Quirks

  1. PHP Version Mismatches:

    • Issue: Polyfill may not work if composer.json enforces a higher PHP version than your server.
    • Fix: Use platform config:
      "config": {
          "platform": {
              "php": "8.1"
          }
      }
      
  2. PCRE Version Warnings:

    • Symptom: grapheme_* functions fail with PCRE <10.44.
    • Fix: Upgrade PCRE or suppress warnings:
      error_reporting(E_ALL & ~E_WARNING);
      

Extension Points

  1. Custom Polyfill Behavior:

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