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

symfony/polyfill-php80

Backport of PHP 8.0 core features for older runtimes. Adds Stringable, fdiv, ValueError/UnhandledMatchError, FILTER_VALIDATE_BOOL, get_debug_type, PhpToken, preg_last_error_msg, str_contains/starts_with/ends_with, and get_resource_id.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/polyfill-php80
    

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

  2. First Use Case: Replace legacy string checks with modern PHP 8.0+ methods:

    // Before (PHP 7.4)
    if (strpos($string, 'admin') !== false) {
        // Handle match
    }
    
    // After (works on PHP 7.2+ with polyfill)
    if (str_contains($string, 'admin')) {
        // Handle match
    }
    
  3. Verify Compatibility: Check if your environment supports the polyfill by running:

    php -r "echo PHP_VERSION; var_dump(class_exists('Stringable'));"
    

    Should output 7.28.0 and true for Stringable.

Where to Look First

  • README: Focus on the list of polyfilled features to identify relevant methods for your Laravel app (e.g., str_contains, ValueError).
  • Laravel Integration: No framework-specific setup is required. Use polyfilled functions directly in controllers, services, or validation logic.
  • Testing: Run php artisan test to ensure polyfilled methods work as expected across your PHP version range.

Implementation Patterns

Usage Patterns

  1. String Manipulation: Replace strpos()/substr() checks with polyfilled methods:

    // Validation in Laravel Form Requests
    public function rules()
    {
        return [
            'input' => ['string', function ($attribute, $value, $fail) {
                if (str_contains($value, 'admin')) {
                    $fail('Admin keywords not allowed.');
                }
            }],
        ];
    }
    
  2. Type Safety with Stringable: Use in DTOs or API responses to enforce type consistency:

    class ApiResponse implements Stringable
    {
        public function __toString(): string
        {
            return json_encode($this->data);
        }
    }
    
  3. Error Handling: Replace custom InvalidArgumentException with ValueError:

    public function parseInput($input)
    {
        if (!is_string($input)) {
            throw new ValueError('Input must be a string.');
        }
        // ...
    }
    
  4. Floating-Point Math: Use fdiv() for precise division (avoids PHP 7.x’s div precision issues):

    $result = fdiv(1, 3); // Returns 0.3333333333333333 instead of 0.33333333333333331
    
  5. Regex Error Handling: Catch regex errors with preg_last_error_msg():

    if (!preg_match('/pattern/', $input)) {
        $error = preg_last_error_msg();
        Log::error("Regex failed: {$error}");
    }
    

Workflows

  1. Incremental Adoption:

    • Start with non-critical features (e.g., str_contains in validation).
    • Gradually replace legacy logic (e.g., strposstr_starts_with).
    • Use if (PHP_VERSION >= 8.0) checks temporarily to isolate polyfill-dependent code.
  2. Laravel Package Development:

    • Use polyfills in reusable packages to support both PHP 7.4+ and 8.0+:
      // In a validation rule package
      if (str_contains($value, 'invalid')) {
          return false;
      }
      
    • Document the minimum PHP version requirement in your package’s composer.json.
  3. Testing Across PHP Versions:

    • Use Laravel’s phpunit.xml to test on multiple PHP versions:
      <php>
          <env name="PHP_VERSION" value="7.4"/>
          <env name="PHP_VERSION" value="8.0"/>
      </php>
      
    • Focus tests on polyfilled methods (e.g., str_contains, ValueError).

Integration Tips

  1. Avoid Conflicts:

    • Search for custom implementations of polyfilled functions:
      grep -r "str_contains\|ValueError\|Stringable" app/
      
    • Rename conflicting classes/methods if needed (e.g., MyValueErrorCustomValueError).
  2. Performance Considerations:

    • Benchmark polyfilled functions in critical paths (e.g., fdiv in financial calculations).
    • Use native PHP 8.0+ functions where possible after upgrading.
  3. IDE Support:

    • Enable PHP 8.0+ features in your IDE (e.g., PHPStorm’s "Language Level") to get autocompletion for polyfilled methods.
    • Add @phpstan-ignore-next-line for static analysis tools if they flag polyfilled types.
  4. Dependency Management:

    • Pin the polyfill version in composer.json for stability:
      "symfony/polyfill-php80": "^1.35"
      
    • Update during Laravel major version upgrades (e.g., Laravel 9+ drops PHP 7.4 support).

Gotchas and Tips

Pitfalls

  1. Custom Implementations:

    • Issue: Conflicts if your code or a package defines str_contains() or ValueError before the polyfill loads.
    • Fix: Rename conflicting classes/methods or load the polyfill first in composer.json:
      "autoload": {
          "psr-4": {
              "App\\": "app/",
              "Symfony\\Polyfill\\": "vendor/symfony/polyfill-php80/"
          }
      }
      
  2. Type System Quirks:

    • Issue: Stringable polyfill may not work with PHP 7.4’s type system (e.g., return type hints).
    • Fix: Use runtime checks:
      if (interface_exists('Stringable') && $obj instanceof Stringable) {
          // Safe to use __toString()
      }
      
  3. Precision Warnings:

    • Issue: fdiv() may still have precision limitations in PHP 7.x (not identical to PHP 8.0’s native fdiv).
    • Fix: Test edge cases (e.g., fdiv(1, 10)) and document limitations.
  4. Regex Edge Cases:

    • Issue: preg_last_error_msg() may not cover all regex errors (e.g., stack overflows).
    • Fix: Fall back to preg_last_error() for unsupported cases.
  5. Laravel Service Providers:

    • Issue: Polyfilled classes may not autoload in some Laravel contexts (rare).
    • Fix: Explicitly require the polyfill in a service provider:
      use Symfony\Polyfill\Php80\Stringable;
      

Debugging

  1. Verify Polyfill Loading:

    • Check if polyfilled functions are available:
      var_dump(function_exists('str_contains')); // Should return true
      
    • Use composer show symfony/polyfill-php80 to confirm installation.
  2. Common Errors:

    • "Class not found": Ensure the polyfill is autoloaded (check composer dump-autoload).
    • Method not found: Verify PHP version compatibility (e.g., str_contains requires PHP 7.2+).
    • Type errors: Use @phpstan-ignore-line for static analysis tools.
  3. Performance Profiling:

    • Use Laravel Debugbar or Xdebug to compare polyfilled vs. native function performance:
      $start = microtime(true);
      str_contains($haystack, $needle);
      $time = microtime(true) - $start;
      

Tips

  1. Leverage match Expressions:

    • Use UnhandledMatchError for exhaustive match expressions (PHP 8.0+):
      $result = match ($status) {
          'active' => 'Active',
          'inactive' => 'Inactive',
          default => throw new UnhandledMatchError($status),
      };
      
  2. Validation Shortcuts:

    • Use FILTER_VALIDATE_BOOL for boolean input parsing:
      $isActive = filter_var($input, FILTER_VALIDATE_BOOL);
      
  3. Debugging with get_debug_type:

    • Replace gettype() with get_debug_type() for clearer output:
      dd(get_debug_type($variable)); // e.g., "array(3)" instead of "array"
      
  4. Resource Handling:

    • Use get_resource_id() for resource comparison:
      if (get_resource_id($resource1)
      
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