Skip to content

Commit

Permalink
[11.x] feat: introduce option to change default Number currency (#53022)
Browse files Browse the repository at this point in the history
* feat: add perWeek option to Limit

* feat: add perWeek option to Limit

* feat: add perMonth option to Limit

* feat: add perMonth option to Limit

* revert

* feat: introduce option to set default currency and override it

* feat: introduce option to set default currency and override it
  • Loading branch information
sts-ryan-holton authored Oct 4, 2024
1 parent d9bb513 commit 2747a5f
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ class Number
*/
protected static $locale = 'en';

/**
* The current default currency.
*
* @var string
*/
protected static $currency = 'USD';

/**
* Format the given number according to the current locale.
*
Expand Down Expand Up @@ -115,13 +122,13 @@ public static function percentage(int|float $number, int $precision = 0, ?int $m
* @param string|null $locale
* @return string|false
*/
public static function currency(int|float $number, string $in = 'USD', ?string $locale = null)
public static function currency(int|float $number, string $in = '', ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();

$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::CURRENCY);

return $formatter->formatCurrency($number, $in);
return $formatter->formatCurrency($number, ! empty($in) ? $in : static::$currency);
}

/**
Expand Down Expand Up @@ -284,6 +291,22 @@ public static function withLocale(string $locale, callable $callback)
return tap($callback(), fn () => static::useLocale($previousLocale));
}

/**
* Execute the given callback using the given currency.
*
* @param string $currency
* @param callable $callback
* @return mixed
*/
public static function withCurrency(string $currency, callable $callback)
{
$previousLCurrency = static::$currency;

static::useCurrency($currency);

return tap($callback(), fn () => static::useCurrency($previousLCurrency));
}

/**
* Set the default locale.
*
Expand All @@ -295,6 +318,17 @@ public static function useLocale(string $locale)
static::$locale = $locale;
}

/**
* Set the default currency.
*
* @param string $currency
* @return void
*/
public static function useCurrency(string $currency)
{
static::$currency = $currency;
}

/**
* Ensure the "intl" PHP extension is installed.
*
Expand Down

0 comments on commit 2747a5f

Please sign in to comment.