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. Provides json_validate, Override attribute, mb_str_pad, str_increment/str_decrement, Date* exceptions, SQLite3Exception, and updated ldap/stream context APIs.

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
    

    For production environments, use --no-dev if the polyfill isn't needed in runtime:

    composer require symfony/polyfill-php83 --no-dev
    
  2. First Use Case: Use json_validate for stricter JSON validation in API requests:

    use Symfony\Polyfill\Php83\JsonValidate;
    
    $jsonString = '{"key": "value"}';
    if (!JsonValidate::validate($jsonString)) {
        abort(422, 'Invalid JSON payload');
    }
    
  3. Where to Look First:

    • Documentation: Symfony Polyfill README for general usage.
    • Source Code: symfony/polyfill-php83 for implementation details and edge cases.
    • Laravel Integration: Focus on json_validate, str_increment, and Override for immediate Laravel-specific benefits.

Implementation Patterns

Usage Patterns

  1. JSON Validation in API Requests: Replace manual JSON parsing with json_validate in Laravel controllers or middleware:

    use Symfony\Polyfill\Php83\JsonValidate;
    
    public function store(Request $request)
    {
        $jsonPayload = $request->json()->all();
        if (!JsonValidate::validate(json_encode($jsonPayload))) {
            return response()->json(['error' => 'Invalid JSON'], 422);
        }
        // Proceed with validated data
    }
    
  2. String Increment/Decrement for Versioning: Use str_increment and str_decrement for version strings or sequential IDs:

    use Symfony\Polyfill\Php83\StringIncrement;
    
    $version = 'v1.0.0';
    $nextVersion = StringIncrement::increment($version); // 'v1.0.1'
    
  3. Method Override Attribute: Mark overridden methods with #[Override] for better IDE support and static analysis:

    use Symfony\Polyfill\Php83\Override;
    
    class MyService extends BaseService
    {
        #[Override]
        public function handle(): void
        {
            // IDE will now recognize this as an override
        }
    }
    
  4. Modern Exception Handling: Replace legacy exceptions with DateTimeException or SQLite3Exception:

    use Symfony\Polyfill\Php83\DateTimeException;
    
    try {
        $date = new DateTime('invalid');
    } catch (DateTimeException $e) {
        report($e);
    }
    

Workflows

  1. Incremental Adoption: Start with non-critical features (e.g., Override attribute) before adopting performance-sensitive ones (e.g., json_validate). Example workflow:

    • Week 1: Add Override attribute to custom traits.
    • Week 2: Replace manual JSON parsing with json_validate.
    • Week 3: Refactor versioning logic to use str_increment.
  2. Testing: Write unit tests for polyfill usage, especially for edge cases like:

    • Invalid JSON strings in json_validate.
    • Numeric strings beyond PHP_INT_MAX in str_increment.
    • Multibyte strings in mb_str_pad.
  3. Benchmarking: Test performance impact in critical paths (e.g., API endpoints) using:

    php artisan tinker
    >>> $start = microtime(true);
    >>> for ($i = 0; $i < 10000; $i++) { JsonValidate::validate('{}'); }
    >>> echo microtime(true) - $start;
    

Integration Tips

  1. Laravel Service Providers: Create a custom helper class to wrap polyfill functions for consistency:

    // app/Helpers/PolyfillHelper.php
    namespace App\Helpers;
    
    use Symfony\Polyfill\Php83\JsonValidate;
    use Symfony\Polyfill\Php83\StringIncrement;
    
    class PolyfillHelper
    {
        public static function validateJson(string $json): bool
        {
            return JsonValidate::validate($json);
        }
    
        public static function incrementVersion(string $version): string
        {
            return StringIncrement::increment($version);
        }
    }
    
  2. Middleware for JSON Validation: Add a middleware to validate JSON payloads globally:

    // app/Http/Middleware/ValidateJson.php
    namespace App\Http\Middleware;
    
    use Closure;
    use Symfony\Polyfill\Php83\JsonValidate;
    
    class ValidateJson
    {
        public function handle($request, Closure $next)
        {
            if ($request->isJson() && !JsonValidate::validate($request->getContent())) {
                abort(422, 'Invalid JSON payload');
            }
            return $next($request);
        }
    }
    
  3. Custom Traits for Polyfill Usage: Create reusable traits for common polyfill patterns:

    // app/Traits/UsesPolyfills.php
    namespace App\Traits;
    
    use Symfony\Polyfill\Php83\JsonValidate;
    use Symfony\Polyfill\Php83\StringIncrement;
    
    trait UsesPolyfills
    {
        protected function validateJson(string $json): bool
        {
            return JsonValidate::validate($json);
        }
    
        protected function incrementString(string $str): string
        {
            return StringIncrement::increment($str);
        }
    }
    
  4. Exception Handling: Extend Laravel’s exception handler to log polyfill-specific exceptions:

    // app/Exceptions/Handler.php
    use Symfony\Polyfill\Php83\DateTimeException;
    use Symfony\Polyfill\Php83\SQLite3Exception;
    
    public function report(Throwable $exception)
    {
        if ($exception instanceof DateTimeException || $exception instanceof SQLite3Exception) {
            Log::error('Polyfill exception', ['exception' => $exception]);
        }
        parent::report($exception);
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • json_validate may introduce slight overhead in high-traffic APIs. Benchmark before widespread adoption.
    • Avoid using str_increment/str_decrement in tight loops for performance-critical code.
  2. IDE Support:

    • Some IDEs (e.g., PHPStorm) may not recognize polyfill functions immediately. Restart the IDE or invalidate caches.
    • Use @method annotations in PHPDoc for custom helper methods to improve autocompletion:
      /**
       * @method static bool validate(string $json)
       */
      class PolyfillHelper {}
      
  3. PHP Version-Specific Behavior:

    • Polyfills may behave differently than native PHP 8.3 functions. Test thoroughly on your target PHP version.
    • Example: mb_str_pad polyfill may handle edge cases (e.g., invalid encodings) differently than the native function.
  4. Dependency Conflicts:

    • Rare but possible conflicts with other polyfill packages (e.g., symfony/polyfill-mbstring). Run:
      composer require symfony/polyfill-php83 --dry-run --prefer-lowest
      
      to check for conflicts.
  5. Null Handling:

    • Some polyfills (e.g., mb_str_pad) may not handle null inputs gracefully. Validate inputs explicitly:
      if ($str === null) {
          throw new \InvalidArgumentException('String cannot be null');
      }
      

Debugging

  1. Polyfill Not Loading:

    • Ensure the package is installed and autoloaded. Run:
      composer dump-autoload
      
    • Verify the namespace is correct (e.g., Symfony\Polyfill\Php83\JsonValidate).
  2. Function Not Found Errors:

    • Check for typos in function names (e.g., JsonValidate::validate vs. json_validate).
    • Ensure you’re using the correct namespace (e.g., use Symfony\Polyfill\Php83\JsonValidate;).
  3. Edge Cases:

    • str_increment with Large Numbers: Test with strings representing numbers beyond PHP_INT_MAX (e.g., '99999999999999999999').
    • mb_str_pad with Invalid Encodings: Handle encoding errors explicitly:
      try {
          mb_str_pad($str, 10, ' ', 'UTF-8');
      } catch (\InvalidArgumentException $e) {
          // Fallback or log error
      }
      
  4. Override Attribute Not Recognized:

    • Ensure your PHP version supports attributes (PHP 8.0+). For
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