LocalizedString::getLanguageRedis()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
1
<?php
2
3
/*
4
 * This file is part of the PhpBotFramework.
5
 *
6
 * PhpBotFramework is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, version 3.
9
 *
10
 * PhpBotFramework is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace PhpBotFramework\Localization;
20
21
use PhpBotFramework\Exceptions\BotException;
22
23
/**
24
 * \class LocalizedString
25
 * \brief Get a localized string using user language and localization files.
26
 */
27
trait LocalizedString
28
{
29
    /** @} */
30
31
    abstract public function getLanguageRedis(string $default_language = 'en', int $expiring_time = 86400) : string;
32
33
    abstract public function loadCurrentLocalization(string $dir = '') : bool;
34
35
    /**
36
     * \addtogroup Localization Localization
37
     * @{
38
     */
39
40
    /** @internal
41
      * \brief Reference to the bot. */
42
    protected $bot;
43
44
    /** @internal
45
      * \brief Current user/group language. */
46
    public $language;
47
48
    /** @internal
49
      * \brief Store the localizated strings. */
50
    protected $local;
51
52
    /**
53
     * \brief Get a localized string giving an index.
54
     * \details Using LocalizedString::language this method get the string of the index given localized string in language of the current user/group.
55
     * This method will load the language first, using PhpBotFramework\Localization\Language::getLanguage(), if the language has not been set.
56
     * If the localization file for the user/group language has not been load yet, it will load it (load only the single localization file if the bot is using webhook, load all otherwise).
57
     * @param string $index Index of the localized string to get.
58
     * @return string Localized string in the current user/group language.
59
     */
60
    public function getStr($index)
61
    {
62
        if (!isset($this->language)) {
63
            $this->getLanguageRedis();
64
        }
65
66
        $this->loadCurrentLocalization();
67
68
        // Check if the requested string exists
69
        if (isset($this->local[$this->language][$index])) {
70
            return $this->local[$this->language][$index];
71
        }
72
73
        throw new BotException("Index '$index' is not set for {$this->language}");
74
    }
75
76
    /** @} */
77
}
78