Skip to content

Commit

Permalink
Throw if extension is not installed when using NumberFormatter wrapper
Browse files Browse the repository at this point in the history
As discussed in #internals, this seems to be a good compromise when the extension is not used. Instead of testing against the exception in the tests, I just skipped the test if the extension is missing, as that is what we do in the InteractsWithRedis testing trait.
  • Loading branch information
caendesilva committed Nov 1, 2023
1 parent 21ed5e0 commit 4520eb2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Support;

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

Expand All @@ -18,6 +19,8 @@ class Number
*/
public static function toHuman($number, $locale = 'en')
{
static::needsIntlExtension();

$formatter = new NumberFormatter($locale, NumberFormatter::SPELLOUT);

return $formatter->format($number);
Expand All @@ -40,4 +43,18 @@ public static function bytesToHuman($bytes, $precision = 2)

return sprintf('%s %s', round($bytes, $precision), $units[$i]);
}

/**
* Some of the helper methods are wrappers for the PHP intl extension,
* and thus require it to be installed on the server. If it's not
* installed, we instead throw an exception from this method.
*
* @return void
*/
protected static function needsIntlExtension()
{
if (! extension_loaded('intl')) {
throw new RuntimeException('The intl PHP extension is required to use this helper.');
}
}
}
11 changes: 11 additions & 0 deletions tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ class SupportNumberTest extends TestCase
{
public function testToHuman()
{
$this->needsIntlExtension();

$this->assertSame('zero', Number::toHuman(0));
$this->assertSame('one', Number::toHuman(1));
$this->assertSame('ten', Number::toHuman(10));
Expand All @@ -34,6 +36,8 @@ public function testToHuman()

public function testToHumanWithDifferentLocale()
{
$this->needsIntlExtension();

$this->assertSame('cent vingt-trois', Number::toHuman(123, 'fr'));

$this->assertSame('ein­hundert­drei­und­zwanzig', Number::toHuman(123, 'de'));
Expand All @@ -56,4 +60,11 @@ public function testBytesToHuman()
$this->assertSame('1 YB', Number::bytesToHuman(1024 ** 8));
$this->assertSame('1024 YB', Number::bytesToHuman(1024 ** 9));
}

protected function needsIntlExtension()
{
if (!extension_loaded('intl')) {
$this->markTestSkipped('The intl extension is not installed. Please install the extension to enable ' . __CLASS__);
}
}
}

0 comments on commit 4520eb2

Please sign in to comment.