New in Symfony 4.3: Simpler access to Intl data
April 16, 2019 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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\Countries;
use Symfony\Component\Intl\Currencies;
use Symfony\Component\Intl\Languages;
\Locale::setDefault('en');
$languages = Languages::getNames();
// => ['ab' => 'Abkhazian', ...]
$language = Languages::getName('de');
// => 'German'
$countries = Countries::getNames();
// => ['AF' => 'Afghanistan', ...]
$country = Countries::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);
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.