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 Intl Icu Laravel Package

symfony/polyfill-intl-icu

Fallback implementations for PHP’s Intl ICU features when the intl extension isn’t installed. Provides limited “en” locale support for intl error functions plus Collator, NumberFormatter, Locale, IntlDateFormatter and IntlListFormatter.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require symfony/polyfill-intl-icu:^1.34.0
    
    • No additional configuration is required. The polyfill automatically replaces missing intl functionality.
  2. First Use Case: RTL Detection Check if a locale is right-to-left (e.g., Arabic, Hebrew) without requiring the intl extension:

    use Symfony\Component\Polyfill\Intl\Icu;
    
    if (Icu\locale_is_right_to_left('ar')) {
        // Apply RTL-specific CSS or layout adjustments
        return view('rtl-layout');
    }
    
  3. First Use Case: Basic Formatting Use NumberFormatter or IntlDateFormatter in environments without the intl extension:

    use Symfony\Component\Polyfill\Intl\Icu;
    
    $formatter = new Icu\NumberFormatter('en_US', Icu\NumberFormatter::CURRENCY);
    echo $formatter->format(1234.56); // Outputs: $1,234.56 (English fallback)
    
  4. Verify PHP 8.5 Compatibility Test IntlListFormatter (added in v1.34.0) on PHP 8.5:

    $formatter = new Icu\IntlListFormatter('en', Icu\IntlListFormatter::LONG);
    echo $formatter->format(['Apple', 'Banana', 'Cherry']); // Outputs: "Apple, Banana, and Cherry"
    

Implementation Patterns

Workflows

1. RTL-Aware UI Adjustments

  • Pattern: Dynamically apply RTL-specific styles or layouts based on locale.
  • Example:
    // In a Laravel controller or Blade directive
    public function getLayout($locale)
    {
        if (Icu\locale_is_right_to_left($locale)) {
            return view('layouts.rtl', ['direction' => 'rtl']);
        }
        return view('layouts.ltr', ['direction' => 'ltr']);
    }
    
  • Integration: Use with Laravel’s localization system (e.g., App::setLocale()) and frontend frameworks like Tailwind (rtl classes).

2. Fallback Formatting for Non-intl Environments

  • Pattern: Replace intl extension calls with polyfill equivalents in CI/CD, shared hosting, or legacy systems.
  • Example:
    // Instead of:
    // $formatter = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
    
    // Use:
    $formatter = new Icu\NumberFormatter('en_US', Icu\NumberFormatter::CURRENCY);
    
  • Integration: Update service providers or helper classes to instantiate ICU classes via the polyfill.

3. PHP 8.5 List Formatting

  • Pattern: Leverage IntlListFormatter for localized list patterns (e.g., "A, B, and C") in PHP 8.5.
  • Example:
    $items = ['Apple', 'Banana', 'Cherry'];
    $formatter = new Icu\IntlListFormatter('en', Icu\IntlListFormatter::LONG);
    $formatted = $formatter->format($items); // "Apple, Banana, and Cherry"
    
  • Integration: Use in Blade templates or API responses for consistent list formatting across locales.

4. Collator for Basic Sorting

  • Pattern: Use Collator for simple sorting (e.g., search filters, admin panels) where intl is unavailable.
  • Example:
    $collator = new Icu\Collator('en');
    $sorted = $collator->sort(['banana', 'apple', 'cherry']);
    
  • Integration: Replace native Collator instantiations in sorting logic (e.g., Eloquent queries, collections).

5. Runtime Extension Check

  • Pattern: Log polyfill usage to plan for future intl extension upgrades.
  • Example:
    if (!extension_loaded('intl')) {
        Log::info('Using ICU polyfill for Intl functionality');
    }
    

Integration Tips

  1. Laravel Service Providers Bind ICU classes to the container for dependency injection:

    // In AppServiceProvider
    $this->app->bind(Icu\NumberFormatter::class, function ($app) {
        return new Icu\NumberFormatter(...);
    });
    
  2. Blade Directives Create a Blade directive for RTL detection:

    // In AppServiceProvider
    Blade::directive('rtl', function ($locale) {
        return "<?php if (\\Symfony\\Component\\Polyfill\\Intl\\Icu\\locale_is_right_to_left({$locale})): ?>";
    });
    

    Usage:

    @rtl('ar')
        <div class="rtl-class">...</div>
    @endrtl
    
  3. Testing Mock ICU classes in PHPUnit to test polyfill behavior:

    $this->partialMockBuilder(Icu\NumberFormatter::class)
        ->disableOriginalConstructor()
        ->setMethods(['format'])
        ->getMock();
    
  4. Performance Optimization Cache Collator or IntlListFormatter instances if used frequently:

    $collator = Cache::remember('collator_en', 3600, function () {
        return new Icu\Collator('en');
    });
    
  5. Environment-Specific Configuration Use Laravel’s config('app.env') to conditionally load ICU features:

    if (app()->environment('production') && !extension_loaded('intl')) {
        // Enable polyfill features
    }
    

Gotchas and Tips

Pitfalls

  1. English-Only Fallbacks

    • The polyfill defaults to English formatting for NumberFormatter, IntlDateFormatter, and IntlListFormatter. Non-English locales (e.g., th_TH, hi_IN) will produce incorrect results.
    • Fix: Use only for English or as a temporary fallback. Plan for ext-intl upgrades for full i18n support.
  2. RTL Detection Limitations

    • locale_is_right_to_left() may not handle all edge cases (e.g., mixed-script content like Arabic + Latin).
    • Fix: Test thoroughly with target locales (ar, he, fa) and validate UI responses (e.g., CSS classes, form alignment).
  3. Performance Overhead

    • Collator::compare() and IntlListFormatter are significantly slower than native intl (3–5x overhead).
    • Fix: Benchmark critical paths (e.g., bulk sorting) and cache instances if performance is critical.
  4. PHP 8.5-Specific Issues

    • While IntlListFormatter is supported in v1.34.0, ensure compatibility with Laravel’s PHP version constraints (e.g., 8.1+).
    • Fix: Test on PHP 8.5 early and monitor for regressions.
  5. Non-Exhaustive Coverage

    • The polyfill does not support all ICU features (e.g., custom collation rules, script-specific formatting).
    • Fix: Document limitations and avoid relying on unsupported features.
  6. Locale Validation

    • The polyfill may not validate all locale strings (e.g., invalid codes like xx_XX).
    • Fix: Sanitize locales before passing to ICU classes:
      $locale = preg_replace('/[^a-zA-Z_-]/', '', $locale);
      

Debugging Tips

  1. Check for Polyfill Usage Log when the polyfill is active to identify areas for optimization:

    if (!extension_loaded('intl')) {
        Log::debug('ICU polyfill active: ', [
            'class' => Icu\NumberFormatter::class,
            'method' => 'format',
        ]);
    }
    
  2. Validate RTL Detection Test with known RTL locales:

    assert(Icu\locale_is_right_to_left('ar') === true);
    assert(Icu\locale_is_right_to_left('en') === false);
    
  3. Compare Polyfill vs. Native Performance Benchmark critical operations:

    $data = range(1, 1000);
    $start = microtime(true);
    usort($data, fn($a, $b) => (new Icu\Collator('en'))->compare($a, $b));
    $time = microtime(true) - $start;
    Log::info("Polyfill sort time: {$time}s");
    
  4. Inspect Formatting Outputs Verify NumberFormatter and IntlDateFormatter outputs match expectations:

    $formatter = new Icu\NumberFormatter('en_US', Icu\NumberFormatter
    
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