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

Lara Asp Formatter Laravel Package

lastdragon-ru/lara-asp-formatter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lastdragon-ru/lara-asp-formatter
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="LastDragon\LaraAspFormatter\LaraAspFormatterServiceProvider" --tag="config"
    
  2. First Use Case: Format a number or date using the built-in Intl wrappers:

    use LastDragon\LaraAspFormatter\Facades\AspFormatter;
    
    // Format a number (e.g., 1000 to "1,000")
    $formattedNumber = AspFormatter::formatNumber(1000, 'en_US');
    
    // Format a date (e.g., timestamp to "MM/dd/yyyy")
    $formattedDate = AspFormatter::formatDate(now(), 'MM/dd/yyyy', 'en_US');
    
  3. Check the Config: Review config/lara-asp-formatter.php for default locales, formats, and customizations.


Implementation Patterns

Core Workflows

  1. Locale-Aware Formatting: Use the facade or service container to dynamically format values based on user locale:

    $locale = app()->getLocale(); // e.g., 'fr_FR'
    $formattedPrice = AspFormatter::formatNumber(1234.56, 'currency', $locale);
    
  2. Custom Format Definitions: Define reusable formats in config/lara-asp-formatter.php:

    'custom_formats' => [
        'short_date' => 'MMM d, yyyy', // e.g., "Jan 1, 2023"
        'file_size'  => '::.2f B',     // e.g., "1.23 KB"
    ],
    

    Use them in code:

    $formattedDate = AspFormatter::formatDate(now(), 'short_date');
    
  3. Integration with Laravel Views: Inject the formatter into Blade templates via a helper or service:

    // In a controller
    return view('dashboard', ['formatter' => AspFormatter::class]);
    
    <!-- In Blade -->
    {{ $formatter::formatNumber($value, 'en_US') }}
    
  4. Request-Based Formatting: Attach formatting logic to incoming requests (e.g., API responses):

    use Illuminate\Http\Resources\Json\JsonResource;
    
    class UserResource extends JsonResource {
        public function toArray($request) {
            return [
                'name' => $this->name,
                'created_at' => AspFormatter::formatDate($this->created_at, 'short_date', $request->locale),
            ];
        }
    }
    
  5. Validation Feedback: Use the formatter to display user-friendly validation messages:

    $validator = Validator::make($data, [
        'price' => 'required|numeric',
    ], [
        'price.numeric' => 'Please enter a valid number (e.g., ' . AspFormatter::formatNumber(1000, 'en_US') . ').',
    ]);
    

Advanced Patterns

  1. Dynamic Locale Switching: Override the default locale per request or context:

    $formattedValue = AspFormatter::setLocale('de_DE')->formatNumber(1000);
    
  2. Chaining Formatters: Combine multiple formats in a single pass:

    $formatted = AspFormatter::formatNumber($value, 'currency', 'en_US')
        ->formatDate($date, 'short_date', 'fr_FR');
    
  3. Testing: Mock the formatter in tests to isolate logic:

    $this->app->instance(\LastDragon\LaraAspFormatter\Contracts\AspFormatter::class, MockFormatter::class);
    
  4. Service Container Binding: Bind custom formatters to the container for dependency injection:

    $this->app->bind('custom.formatter', function () {
        return new CustomFormatter(AspFormatter::class);
    });
    

Gotchas and Tips

Pitfalls

  1. Locale Fallbacks:

    • The package defaults to en_US if the requested locale is unsupported. Explicitly handle fallbacks:
      $locale = $request->locale ?? 'en_US';
      $formatted = AspFormatter::formatNumber(1000, 'currency', $locale);
      
  2. Intl Extension Requirements:

    • Ensure intl PHP extension is enabled. Test with:
      php -m | grep intl
      
    • If missing, install via:
      pecl install intl
      
      or enable in php.ini:
      extension=intl
      
  3. Caching Static Formats:

    • Avoid reformatting the same value repeatedly. Cache results:
      $cacheKey = "formatted_{$value}_{$format}_{$locale}";
      $formatted = cache()->remember($cacheKey, now()->addHours(1), function () use ($value, $format, $locale) {
          return AspFormatter::formatNumber($value, $format, $locale);
      });
      
  4. Date/Time Zone Sensitivity:

    • Formatted dates are sensitive to the system's timezone. Set it explicitly:
      date_default_timezone_set('UTC');
      $formatted = AspFormatter::formatDate(now(), 'yyyy-MM-dd');
      
  5. Custom Format Syntax:

    • Custom formats use IntlDateFormatter/NumberFormatter syntax. Test edge cases:
      // May fail if locale doesn't support the pattern
      AspFormatter::formatDate(now(), 'E, MMM d, yyyy', 'ja_JP');
      

Debugging Tips

  1. Validate Locale Support: Check supported locales with:

    $supportedLocales = AspFormatter::getSupportedLocales();
    
  2. Log Format Errors: Wrap formatting in a try-catch to log unsupported patterns:

    try {
        $formatted = AspFormatter::formatDate($date, $pattern, $locale);
    } catch (\IntlException $e) {
        Log::error("Format failed: {$pattern} for locale {$locale}", ['exception' => $e]);
        $formatted = $date; // Fallback
    }
    
  3. Inspect Raw Intl Objects: Access underlying NumberFormatter/DateFormatter for debugging:

    $formatter = AspFormatter::getNumberFormatter('en_US', \NumberFormatter::CURRENCY);
    var_dump($formatter->getPattern());
    

Extension Points

  1. Custom Formatters: Extend the base formatter for domain-specific logic:

    class AppFormatter extends \LastDragon\LaraAspFormatter\AspFormatter {
        public function formatFileSize(int $bytes, string $locale = 'en_US'): string {
            $units = ['B', 'KB', 'MB', 'GB'];
            $unit = 0;
            while ($bytes > 1024 && $unit < count($units) - 1) {
                $bytes /= 1024;
                $unit++;
            }
            return $this->formatNumber($bytes, '::.2f', $locale) . ' ' . $units[$unit];
        }
    }
    
  2. Service Provider Hooks: Override defaults in the service provider:

    public function register() {
        $this->app->singleton(\LastDragon\LaraAspFormatter\Contracts\AspFormatter::class, function () {
            return new AppFormatter(config('lara-asp-formatter'));
        });
    }
    
  3. Artisan Commands: Add commands to validate or generate formats:

    Artisan::command('formatter:test', function () {
        $this->info(AspFormatter::formatDate(now(), 'yyyy-MM-dd', 'en_US'));
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky