1+ <?php
2+ /**
3+ * Translator class.
4+ * This class provides a way to translate texts by replacing specific strings with their corresponding translations.
5+ *
6+ * @author Sebastiano Racca
7+ * @package TelegramSDK\BotAPI\Utils
8+ * @see docs/02-translating.md
9+ */
10+
11+ declare (strict_types=1 );
12+ namespace TelegramSDK \BotAPI \Utils ;
13+
14+
15+ class Translator{
16+ public ?object $ texts ;
17+ public ?array $ translations ;
18+
19+ /**
20+ * Translator constructor.
21+ *
22+ * @param object $texts The object containing the original texts.
23+ * @param array|null $translations Associative array of the translations to be applied.
24+ */
25+ public function __construct (object $ texts , ?array $ translations = null ){
26+ $ this ->translations = $ translations ;
27+ $ this ->texts = $ texts ;
28+ }
29+
30+ /**
31+ * Translates the given string.
32+ *
33+ * @param string $text The text to be translated.
34+ * @return string The translated text.
35+ */
36+ public function translate (string $ text ): string {
37+ return strtr ($ text , $ this ->translations );
38+ }
39+
40+ /**
41+ * Magic method to dynamically access properties.
42+ *
43+ * @param string $name The name of the property.
44+ * @return mixed The value of the property, translated if applicable.
45+ */
46+ public function __get (string $ name ): mixed {
47+ if (!property_exists ($ this ->texts , $ name ))
48+ return null ;
49+
50+ $ propertyValue = $ this ->texts ->$ name ;
51+
52+ if (is_string ($ propertyValue ))
53+ return $ this ->translate ($ propertyValue );
54+
55+ if (is_object ($ propertyValue ) || is_array ($ propertyValue )){
56+ $ translator = new Translator ($ this ->texts , $ this ->translations );
57+ $ translator ->texts = $ propertyValue ;
58+ return $ translator ;
59+ }
60+
61+ return $ propertyValue ;
62+ }
63+
64+ }
0 commit comments