diff options
author | Igor Scheller <igor.scheller@igorshp.de> | 2018-08-28 22:23:59 +0200 |
---|---|---|
committer | Igor Scheller <igor.scheller@igorshp.de> | 2018-08-29 23:46:31 +0200 |
commit | 427315195bdd379a0207fc9b2aaf69a5b5b86c79 (patch) | |
tree | 678245351333a16c5a5bca129aada4bfd311c23c /src/Helpers/Translator.php | |
parent | df6360044b5c2396b2bee0dfa9e8d744bfa424d5 (diff) |
Moved translation/internationalization to Helpers\Translator class
Diffstat (limited to 'src/Helpers/Translator.php')
-rw-r--r-- | src/Helpers/Translator.php | 105 |
1 files changed, 105 insertions, 0 deletions
diff --git a/src/Helpers/Translator.php b/src/Helpers/Translator.php new file mode 100644 index 00000000..1e953a21 --- /dev/null +++ b/src/Helpers/Translator.php @@ -0,0 +1,105 @@ +<?php + +namespace Engelsystem\Helpers; + +class Translator +{ + /** @var string[] */ + protected $locales; + + /** @var string */ + protected $locale; + + /** @var callable */ + protected $localeChangeCallback; + + /** + * Translator constructor. + * + * @param string $locale + * @param string[] $locales + * @param callable $localeChangeCallback + */ + public function __construct(string $locale, array $locales = [], callable $localeChangeCallback = null) + { + $this->localeChangeCallback = $localeChangeCallback; + + $this->setLocale($locale); + $this->setLocales($locales); + } + + /** + * Get the translation for a given key + * + * @param string $key + * @param array $replace + * @return string + */ + public function translate(string $key, array $replace = []): string + { + $translated = $this->translateGettext($key); + + if (!empty($replace)) { + $translated = call_user_func_array('sprintf', array_merge([$translated], $replace)); + } + + return $translated; + } + + /** + * Translate the key via gettext + * + * @param string $key + * @return string + * @codeCoverageIgnore + */ + protected function translateGettext(string $key): string + { + return _($key); + } + + /** + * @return string + */ + public function getLocale(): string + { + return $this->locale; + } + + /** + * @param string $locale + */ + public function setLocale(string $locale) + { + $this->locale = $locale; + + if (is_callable($this->localeChangeCallback)) { + call_user_func_array($this->localeChangeCallback, [$locale]); + } + } + + /** + * @return string[] + */ + public function getLocales(): array + { + return $this->locales; + } + + /** + * @param string $locale + * @return bool + */ + public function hasLocale(string $locale): bool + { + return isset($this->locales[$locale]); + } + + /** + * @param string[] $locales + */ + public function setLocales(array $locales) + { + $this->locales = $locales; + } +} |