Skip to content

Instantly share code, notes, and snippets.

@lftbrts
Created July 18, 2019 07:52
Show Gist options
  • Save lftbrts/d38cc3df7b51b8a7d51b8ab97c8a90a0 to your computer and use it in GitHub Desktop.
Save lftbrts/d38cc3df7b51b8a7d51b8ab97c8a90a0 to your computer and use it in GitHub Desktop.
Change current system locale and reset after doing stuff
<?php
$locale = new Locale();
$currentLocale = $locale->currentLocale();
# do some stuff
\setLocale(\LC_ALL, 'en.US-UTF8');
#
$locale->resetLocale($currentLocale);
class Locale
{
/**
* @return array
*/
public function currentLocale(): array
{
return \explode(';', \setlocale(LC_ALL, 0));
}
/**
* @param array $locales
*/
public function resetLocale(array $locales): void
{
$skipConstants = [
'LC_PAPER',
'LC_NAME',
'LC_ADDRESS',
'LC_TELEPHONE',
'LC_MEASUREMENT',
'LC_IDENTIFICATION',
];
foreach ($locales as $localeSetting) {
$category = \LC_ALL;
$locale = $localeSetting;
if (false !== \strpos($localeSetting, '=')) {
[$category, $locale] = \explode('=', $localeSetting);
}
if (false === \in_array($category, $skipConstants, true)) {
\setlocale(\constant($category), $locale);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment