Completed
Push — master ( d7f7fe...c1145d )
by Danilo
04:17
created

File::loadAllLocalizations()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 9
cp 0
rs 8.7624
c 0
b 0
f 0
cc 6
eloc 10
nc 5
nop 1
crap 42
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
trait File
24
{
25
26
    /**
27
     * \addtogroup Localization Localization
28
     * \brief Methods to create a localized bot.
29
     * \details Localization files must have this syntax:
30
     * file <code>./localization/en.json</code>:
31
     *
32
     *     {"Hello_Msg": "Hello"}
33
     *
34
     * File <code>./localization/it.json</code>:
35
     *
36
     *     {"Hello_Msg": "Ciao"}
37
     *
38
     * Usage in <code>processMessage()</code>:
39
     *
40
     *     $sendMessage($this->local[$this->language]["Hello_Msg"]);
41
     *
42
     * @{
43
     */
44
45
    /** \brief (<i>Internal</i>)Store the localizated strings. */
46
    protected $local;
47
48
    /** \brief Directory where there are the localization files. */
49
    protected $localization_dir = './localization';
50
51
    /**
52
     * \brief (<i>Internal</i>)Load a localization file into the localized strings array.
53
     * @param string $lang Language to load.
54
     * @param string $dir Directory in which there are the JSON files.
55
     * @return bool True if loaded.
56
     */
57
    protected function loadSingleLanguage(string $lang = 'en', string $dir = './localization') : bool
58
    {
59
        // Name of the file
60
        $filename = "$dir/$lang";
61
62
        // If this language isn't already set
63
        if (!isset($this->local[$lang])) {
64
            // and the file exists
65
            if (file_exists($filename)) {
66
                // Load localization in memory
67
                $this->local[$lang] = json_decode(file_get_contents($filename), true);
68
69
                // We loaded it
70
                return true;
71
            }
72
            // The file doens't exists
73
            return false;
74
        }
75
76
        // The language is already set
77
        return true;
78
    }
79
80
    /**
81
     * \brief Load all localization files (JSON-serialized) from a folder and set them in $local variable.
82
     * \details Save all localization files, saved as json format, from a directory and put the contents in $local variable.
83
     * Each file will be saved into $local with the first two letters of the filename as the index.
84
     * @param string $dir Directory where the localization files are saved.
85
     * @return bool True if the directory could be opened without errors.
86
     */
87
    public function loadAllLanguages(string $dir = './localization') : bool
88
    {
89
        // Open directory
90
        if ($handle = opendir($dir)) {
91
            // Iterate over all files
92
            while (false !== ($file = readdir($handle))) {
93
                // If the file is a JSON data file
94
                if (strlen($file) > 6 && substr($file, -5) === '.json') {
95
                    try {
96
                        // Add the contents of the file to the $local variable, after deserializng it from JSON format
97
                        // The contents will be added with the 2 letter of the file as the index
98
                        $this->local[substr($file, 0, 2)] = json_decode(file_get_contents("$dir/$file"), true);
99
                    } catch (BotException $e) {
100
                        echo $e->getMessage();
101
                    }
102
                }
103
            }
104
            return true;
105
        }
106
        return false;
107
    }
108
109
    /**
110
     * \brief Load localization for current language and mode.
111
     * \details This method will load only the current user/group localization file if the bot is using webhook, all files otherwise.
112
     * @param string $dir Directory where the localization file is stored. If no directory is given (by default) it will load it from $localization_dir (which is ./localization if it is not set).
113
     * @return bool True if the localization has been loaded or it is already loaded.
114
     */
115
    public function loadCurrentLocalization(string $dir = '') : bool
116
    {
117
        // If no dir has been given
118
        if (!isset($dir) || $dir === '') {
119
            // The dir is the default one
120
            $dir = $this->localization_dir;
0 ignored issues
show
Unused Code introduced by
$dir is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
121
        }
122
123
        // If the language of the user is already set in the array containing localizated strings
124
        if (!isset($this->local[$this->language])) {
0 ignored issues
show
Bug introduced by
The property language does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
125
            // Is the bot using webhook?
126
            if (isset($this->_is_webhook)) {
127
                return $this->loadSingleLanguage($this->localization_dir);
128
            } else {
129
                return $this->loadAllLanguages($this->localization_dir);
130
            }
131
        }
132
133
        return false;
134
    }
135
136
    /**
137
     * \brief Set location of localization files.
138
     * @param string $dir Directory where the files are stored.
139
     */
140
    public function setLocalizationDir(string $dir)
141
    {
142
        $this->localization_dir = $dir;
143
    }
144
145
    /** @} */
146
}
147