From 32210e772564193ec3b1388cc3c30fdf81eba231 Mon Sep 17 00:00:00 2001 From: Deeka Wong Date: Mon, 5 Feb 2024 23:05:00 +0800 Subject: [PATCH] Optimized `Number` helper (#554) Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com> --- src/Number.php | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/Number.php b/src/Number.php index fff3730..a55b007 100644 --- a/src/Number.php +++ b/src/Number.php @@ -53,10 +53,18 @@ public static function format(int|float $number, ?int $precision = null, ?int $m * * @return string */ - public static function spell(int|float $number, ?string $locale = null) + public static function spell(int|float $number, ?string $locale = null, ?int $after = null, ?int $until = null) { static::ensureIntlExtensionIsInstalled(); + if (! is_null($after) && $number <= $after) { + return static::format($number, locale: $locale); + } + + if (! is_null($until) && $number >= $until) { + return static::format($number, locale: $locale); + } + $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT); return $formatter->format($number); @@ -127,10 +135,9 @@ public static function fileSize(int|float $bytes, int $precision = 0, ?int $maxP } /** - * Convert the number to its human readable equivalent. + * Convert the number to its human-readable equivalent. * - * @param int $number - * @return string + * @return bool|string */ public static function abbreviate(int|float $number, int $precision = 0, ?int $maxPrecision = null) { @@ -138,10 +145,9 @@ public static function abbreviate(int|float $number, int $precision = 0, ?int $m } /** - * Convert the number to its human readable equivalent. + * Convert the number to its human-readable equivalent. * - * @param int $number - * @return string + * @return bool|string */ public static function forHumans(int|float $number, int $precision = 0, ?int $maxPrecision = null, bool $abbreviate = false) { @@ -222,7 +228,9 @@ protected static function summarize(int|float $number, int $precision = 0, ?int protected static function ensureIntlExtensionIsInstalled() { if (! extension_loaded('intl')) { - throw new RuntimeException('The "intl" PHP extension is required to use this method.'); + $method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']; + + throw new RuntimeException('The "intl" PHP extension is required to use the [' . $method . '] method.'); } } }