* @package Mammut\Locale */ class TranslateXml extends TranslateBase implements iTranslate { /** * @var \SimpleXMLElement */ private $store; public function __construct($basepath, $locale) { $file = $basepath . DIRECTORY_SEPARATOR . $locale . '.xml'; if(!file_exists($file)) throw new \Mammut\IO\FileNotFoundException($file); $this->store = simplexml_load_file($file); } /** * Main translate method. * * Looks after the translated text, based on the key and optional values. * * @param string $key * text base or key to search * @param int $count * count parameter value for the lookup * @param string $gender * genderized selection value for the lookup * @param array $values * @param boolean $nullOnFail * the behaviour on missed translations. if true, the method returns null * instead of the key. * @return string the translated text. if not found, null or the key based on the * $nullOnFail parameter */ public function translate($key, $count = NULL, $gender = NULL, $values = array(), $nullOnFail = false) { if(is_string($gender)) $gender = strtolower($gender); if(!in_array($gender, array(self::MALE,self::FEMALE,self::UNDEF))) $gender = NULL; if(is_scalar($values)) $values = array($values); $search = "@key='{$key}'"; if(is_numeric($count)) $search .= " and (@n='$count' or @n='n' or not(@n))"; else $search .= " and (@n='n' or not(@n))"; switch($gender) { case self::MALE: $search .= " and (@gender='m' or not(@gender))"; break; case self::FEMALE: $search .= " and (@gender='f' or not(@gender))"; break; default: $search .= " and (@gender='u' or not(@gender))"; break; } $result = $this->store->xpath("//text[{$search}]"); if(count($result) == 1) { $result = (string) $result[0]; foreach($values as $vKey=>$value) $result = str_replace('%' . $vKey, $value, $result); return $result; } else { $xPdAdd = "@key='{$key}'"; foreach($values as $vKey=>$value) { if(is_numeric($vKey) && is_numeric($value)) $xPdAdd .= " and (@n{$vKey}='$value' or @n{$vKey}='n' or not(@n{$vKey}))"; } $xp = "//text[{$xPdAdd}]"; $result = $this->store->xpath($xp); if (empty($result)) return $key.'['.(is_array($values) ? implode('|',$values):$values).']'; $result = (string) $result[0]; foreach($values as $vKey=>$value) $result = str_replace('%' . $vKey, $value, $result); return $result; } return $nullOnFail ? NULL : $key; } public function tr($key, array $param = [], $nullOnFail = false) { return self::translate($key, NULL, NULL, $param, $nullOnFail); } public function trg($key, $gender, array $param = [], $nullOnFail = false) { return self::translate($key, NULL, $gender, $param, $nullOnFail); } public function trn($key, $count, array $param = [], $nullOnFail = false) { return self::translate($key, $count, NULL, $param, $nullOnFail); } }