Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Support\Traits\Macroable;
use NumberFormatter;
use ResourceBundle;
use RuntimeException;

class Number
Expand All @@ -24,6 +25,23 @@ class Number
*/
protected static $currency = 'USD';

/**
* @param string $locale
* @return string
*
* @throws \InvalidArgumentException
*/
public static function validateLocale(string $locale): string
{
$availableLocales = ResourceBundle::getLocales('');

if (! in_array($locale, $availableLocales, true)) {
throw new \InvalidArgumentException("Locale [$locale] is invalid");
}

return $locale;
}

/**
* Format the given number according to the current locale.
*
Expand All @@ -32,11 +50,15 @@ class Number
* @param int|null $maxPrecision
* @param string|null $locale
* @return string|false
*
* @throws \InvalidArgumentException
*/
public static function format(int|float $number, ?int $precision = null, ?int $maxPrecision = null, ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();

$locale = $locale ? static::validateLocale($locale) : null;

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

if (! is_null($maxPrecision)) {
Expand Down
10 changes: 10 additions & 0 deletions tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -314,4 +314,14 @@ public function testTrim()
$this->assertSame(12.3456789, Number::trim(12.3456789));
$this->assertSame(12.3456789, Number::trim(12.34567890000));
}

/**
* Test invalid locale input in format method.
*/
public function testInvalidLocale()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Locale [invalid-locale] is invalid');
Number::format(1234.56, locale: 'invalid-locale');
}
}