New in Symfony 4.3: Simpler access to Intl data

Contributed by
Roland Franssen
in #28846.

The ICU project ("International Components for Unicode") is a widely used set of libraries to provide globalization support for software applications. As part of their mission, they provide localized data commonly needed in projects (e.g. the name of all countries in all languages, the name and basic data of all currencies in all languages, etc.)

The Intl component provides the methods needed to access the localized data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use Symfony\Component\Intl\Intl;

\Locale::setDefault('en');

$languages = Intl::getLanguageBundle()->getLanguageNames();
// => ['ab' => 'Abkhazian', ...]

$language = Intl::getLanguageBundle()->getLanguageName('de');
// => 'German'

$countries = Intl::getRegionBundle()->getCountryNames();
// => ['AF' => 'Afghanistan', ...]

$country = Intl::getRegionBundle()->getCountryName('GB');
// => 'United Kingdom'

$currency = Intl::getCurrencyBundle()->getCurrencyName('INR');
// => 'Indian Rupee'

$symbol = Intl::getCurrencyBundle()->getCurrencySymbol('INR');
// => '₹'

$fractionDigits = Intl::getCurrencyBundle()->getFractionDigits('INR');
// => 2

Although this works nicely, in Symfony 4.3 we improved it to make it even easier and to simplify the underlying class structure. The new code is more concise and easier to read:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use Symfony\Component\Intl\Currencies;
use Symfony\Component\Intl\Languages;
use Symfony\Component\Intl\Regions;

\Locale::setDefault('en');

$languages = Languages::getNames();
// => ['ab' => 'Abkhazian', ...]

$language = Languages::getName('de');
// => 'German'

$countries = Regions::getNames();
// => ['AF' => 'Afghanistan', ...]

$country = Regions::getName('GB');
// => 'United Kingdom'

$currency = Currencies::getName('INR');
// => 'Indian Rupee'

$symbol = Currencies::getSymbol('INR');
// => '₹'

$fractionDigits = Currencies::getFractionDigits('INR');
// => 2

As an added bonus, we've added several exists() methods to check if the given value is a valid region, language, locale, etc.:

1
2
3
4
5
$isValidLanguage = Languages::exists($languageCode);
$isValidScript = Scripts::exists($scriptCode);
$isValidRegion = Regions::exists($regionCode);
$isValidLocale = Locales::exists($localeCode);
$isValidCurrency = Currencies::exists($currencyCode);

Comments

Nice improvements!
See also https://github.com/symfony/symfony/pull/28831 for a follow up PR; adding the Intl timezones 🎉
Another hidden gem is the addition of `exists(): bool` in all data bundles, whereas previously you had to try/catch it.
timezones? Yes, please
It's cleaner, so I like it. :)
Login with SymfonyConnect to post a comment