From 25d2f1c31bf6cbbbe90e19da1d53d1fb0398d79a Mon Sep 17 00:00:00 2001 From: "Hahn Axel (hahn)" <axel.hahn@unibe.ch> Date: Tue, 17 Sep 2024 11:39:57 +0200 Subject: [PATCH] add lang class --- classes/lang.class.php | 62 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 classes/lang.class.php diff --git a/classes/lang.class.php b/classes/lang.class.php new file mode 100644 index 0000000..e5f9d09 --- /dev/null +++ b/classes/lang.class.php @@ -0,0 +1,62 @@ +<?php + + +class lang +{ + + /** + * Language code with 2 digits + * @var string + */ + protected string $sLang = 'en'; + + /** + * Array with all translation texts of a language + * @var array + */ + protected array $aLang = []; + + /** + * Constructor + * @param string $sLang optional: language to set + */ + public function __construct(string $sLang='') + { + if($sLang){ + $this->setLang($sLang); + } + + } + + /** + * Set a Language; it loads a JSON file with translations + * @param string $sLanguageCode 2 digit language code + * @return bool + */ + public function setLang(string $sLanguageCode = ''): bool + { + $sLlangfile = dirname((__DIR__))."/lang/$sLanguageCode.json"; + if (!file_exists($sLlangfile)) { + new Exception("ERROR: Language file $sLlangfile does not exist."); + return false; + } + $aTmp = json_decode(file_get_contents($sLlangfile), 1); + if(!is_array($aTmp)){ + new Exception("ERROR: Language file $sLlangfile is not valid JSON."); + return false; + } + $this->aLang = $aTmp; + $this->sLang = $sLanguageCode; + return true; + } + + /** + * Get the translated text for a given key + * @param string $s + * @return string + */ + public function t($sKeyword): string + { + return $this->aLang[$sKeyword] ?? "MISS [$sKeyword]"; + } +} \ No newline at end of file -- GitLab