From 9c332a906d411063e318519e6cf8ad5b50ad8d84 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Tue, 10 Aug 2021 16:18:50 -0700 Subject: [PATCH] CRM_Utils_AutoClean - Add variant of `swap()` tuned for setting locale This can currently be done with `swap()`, but we may be doing this several times, and `swapLocale()` is a little more pithy and a little more microoptimal. --- CRM/Utils/AutoClean.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/CRM/Utils/AutoClean.php b/CRM/Utils/AutoClean.php index 1be38b0ece..514283f434 100644 --- a/CRM/Utils/AutoClean.php +++ b/CRM/Utils/AutoClean.php @@ -48,6 +48,26 @@ class CRM_Utils_AutoClean { return $ac; } + /** + * Temporarily set the active locale. Cleanup locale when the autoclean handle disappears. + * + * @param string|null $newLocale + * Ex: 'fr_CA' + * @return \CRM_Utils_AutoClean|null + */ + public static function swapLocale(?string $newLocale) { + $oldLocale = $GLOBALS['tsLocale'] ?? NULL; + if ($oldLocale === $newLocale) { + return NULL; + } + + $i18n = \CRM_Core_I18n::singleton(); + $i18n->setLocale($newLocale); + return static::with(function() use ($i18n, $oldLocale) { + $i18n->setLocale($oldLocale); + }); + } + /** * Temporarily swap values using callback functions, and cleanup * when the current context shuts down. -- 2.25.1