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

symfony/polyfill-php83

Symfony Polyfill for PHP 8.3 features on older runtimes. Adds json_validate, Override attribute, mb_str_pad, str_increment/str_decrement, updated LDAP/stream context signatures, Date/SQLite3 exception classes, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer in your Laravel project:

    composer require symfony/polyfill-php83
    

    Or include it via the symfony/polyfill meta-package if you already use other Symfony polyfills.

  2. First Use Case: Use json_validate for JSON payload validation in Laravel request handling:

    use Symfony\Polyfill\Php83\JsonValidate;
    
    $jsonPayload = request()->json()->all();
    $jsonString = json_encode($jsonPayload);
    $isValid = JsonValidate::validate($jsonString);
    
    if (!$isValid) {
        return response()->json(['error' => 'Invalid JSON'], 400);
    }
    
  3. Where to Look First:

    • Polyfill Features: Refer to the README for a list of supported PHP 8.3 features.
    • Laravel Integration: Check if Laravel already uses this polyfill (e.g., in vendor/symfony/polyfill-php83).
    • Usage Examples: Explore the Symfony Polyfill documentation for implementation patterns.

Implementation Patterns

Usage Patterns

  1. Validation Layer: Use json_validate in Laravel middleware or form requests:

    use Symfony\Polyfill\Php83\JsonValidate;
    
    public function handle($request, Closure $next)
    {
        if ($request->isJson()) {
            $json = $request->getContent();
            if (!JsonValidate::validate($json)) {
                return response()->json(['error' => 'Invalid JSON'], 400);
            }
        }
        return $next($request);
    }
    
  2. String Manipulation: Replace custom versioning logic with str_increment/str_decrement:

    use Symfony\Polyfill\Php83\StringFunctions;
    
    $version = 'v1.0';
    $nextVersion = StringFunctions::str_increment($version); // Returns 'v1.1'
    
  3. Error Handling: Use modern exception classes for cleaner error propagation:

    use Symfony\Polyfill\Php83\DateTimeException;
    
    try {
        $date = new DateTime('invalid');
    } catch (DateTimeException $e) {
        Log::error('DateTime error: ' . $e->getMessage());
    }
    
  4. LDAP/SQLite: Polyfill deprecated functions for backward compatibility:

    use Symfony\Polyfill\Php83\LdapFunctions;
    
    $ldapResource = LdapFunctions::ldap_connect_wallet(...);
    

Workflows

  1. Gradual Migration:

    • Start with non-critical features (e.g., DateTimeException).
    • Replace custom implementations (e.g., JSON validation) with polyfilled methods.
    • Update type hints and IDE configurations incrementally.
  2. Testing:

    • Write unit tests for polyfill-specific logic:
      public function testJsonValidation()
      {
          $this->assertTrue(JsonValidate::validate('{"valid": true}'));
          $this->assertFalse(JsonValidate::validate('invalid json'));
      }
      
    • Use Laravel’s testing tools (e.g., HttpTests) to validate polyfill behavior in API endpoints.
  3. Configuration:

    • No Laravel-specific configuration is required. Polyfills are autoloaded via Composer.

Integration Tips

  1. Laravel Service Providers: Bind polyfill classes in a service provider if needed:

    public function register()
    {
        $this->app->singleton('jsonValidator', function () {
            return new class {
                public function validate(string $json): bool
                {
                    return JsonValidate::validate($json);
                }
            };
        });
    }
    
  2. Custom Helpers: Create helper methods in Laravel’s app/Helpers or a service class:

    namespace App\Helpers;
    
    use Symfony\Polyfill\Php83\StringFunctions;
    
    class StringHelper
    {
        public static function incrementVersion(string $version): string
        {
            return StringFunctions::str_increment($version);
        }
    }
    
  3. IDE Support: Ensure your IDE recognizes polyfill classes by configuring autoloading:

    • PHPStorm: Go to File > Settings > PHP > Include Path and add vendor/autoload.php.
    • VSCode: Use the PHP Intelephense extension with Composer autoloading enabled.

Gotchas and Tips

Pitfalls

  1. False Assumptions:

    • Polyfills may not handle edge cases identically to PHP 8.3’s native implementations. Test thoroughly, especially for:
      • str_increment/str_decrement with non-string inputs or large numbers.
      • json_validate with malformed JSON (e.g., trailing commas).
  2. Performance Overhead:

    • Polyfills introduce abstraction layers. Benchmark critical paths (e.g., json_validate in high-traffic APIs) using Laravel’s bench() or Blackfire.
  3. IDE/Tooling Issues:

    • Static analyzers (PHPStan, Psalm) may flag polyfill methods as undefined. Configure them to recognize Symfony polyfills:
      # phpstan.neon
      parameters:
          bootstrapFiles:
              - vendor/autoload.php
      
  4. PHP Version Conflicts:

    • Polyfills may not work on very old PHP versions (e.g., PHP 7.3). Enforce a minimum PHP version in composer.json:
      "config": {
          "platform": {
              "php": "8.1"
          }
      }
      
  5. Override Attribute:

    • The Override attribute may cause issues with Laravel’s autoloading or IDE tooling. Ensure your IDE supports Symfony’s polyfill attributes.

Debugging Tips

  1. Polyfill-Specific Errors:

    • Wrap polyfill calls in try-catch blocks for graceful degradation:
      try {
          $result = StringFunctions::str_increment($input);
      } catch (\Throwable $e) {
          Log::error('Polyfill error: ' . $e->getMessage());
          $result = fallbackLogic($input);
      }
      
  2. Logging:

    • Log polyfill usage and edge cases for debugging:
      Log::debug('Using polyfill str_increment for input:', ['input' => $input]);
      
  3. Testing Edge Cases:

    • Test polyfills with invalid inputs to ensure robust error handling:
      $this->assertFalse(JsonValidate::validate(''));
      $this->assertFalse(JsonValidate::validate(null));
      

Configuration Quirks

  1. Autoloading:

    • Ensure vendor/autoload.php is included in your Laravel project. If using Laravel’s bootstrap/app.php, this is handled automatically.
  2. Composer Dependencies:

    • Avoid version conflicts by pinning the polyfill version in composer.json:
      "require": {
          "symfony/polyfill-php83": "^1.38"
      }
      
  3. Laravel Mix/Webpack:

    • Polyfills are server-side only. No Webpack configuration is required.

Extension Points

  1. Custom Polyfills:

    • Extend or override polyfill behavior by creating wrapper classes:
      class CustomStringFunctions extends StringFunctions
      {
          public static function str_increment(string $str): string
          {
              // Custom logic
              return parent::str_increment($str);
          }
      }
      
  2. Feature Flags:

    • Use Laravel’s config system to toggle polyfill usage:
      if (config('app.use_polyfills')) {
          $result = JsonValidate::validate($json);
      } else {
          $result = customJsonValidate($json);
      }
      
  3. Polyfill Removal:

    • Plan for gradual removal as PHP 8.3 adoption grows. Use Laravel’s config to detect PHP version and disable polyfills:
      if (version_compare(PHP_VERSION, '8.3.0', '<')) {
          // Use polyfills
      } else {
          // Use native PHP 8.3 features
      }
      

Laravel-Specific Tips

  1. Service Container:

    • Bind polyfill classes to Laravel’s service container for dependency injection:
      $this->app->bind(JsonValidate::class, function () {
          return new class {
              public function validate(string $json): bool
              {
                  return \Symfony\Polyfill\Php83\JsonValidate::validate($json);
              }
          };
      });
      
  2. Artisan Commands:

    • Use polyfills in custom Artisan commands for CLI-based string manipulation:
      use Symfony\Polyfill\Php83\StringFunctions;
      
      class Increment
      
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