From 2747a5ffe0d4dcdcc39b0cd3b3dd9892b619c0c4 Mon Sep 17 00:00:00 2001 From: Ryan Holton Date: Fri, 4 Oct 2024 15:09:03 +0100 Subject: [PATCH] [11.x] feat: introduce option to change default Number currency (#53022) * 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 --- src/Illuminate/Support/Number.php | 38 +++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Support/Number.php b/src/Illuminate/Support/Number.php index 24825cdd7308..de0aa188c84f 100644 --- a/src/Illuminate/Support/Number.php +++ b/src/Illuminate/Support/Number.php @@ -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. * @@ -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); } /** @@ -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. * @@ -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. *