Completed
Push — master ( 8470e3...ad08f4 )
by Danilo
03:56
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
trait File
22
{
23
24
    /**
25
     * \addtogroup Localization Localization
26
     * \brief Methods to create a localized bot.
27
     * \details Localization files must have this syntax:
28
     * file <code>./localization/en.json</code>:
29
     *
30
     *     {"Hello_Msg": "Hello"}
31
     *
32
     * File <code>./localization/it.json</code>:
33
     *
34
     *     {"Hello_Msg": "Ciao"}
35
     *
36
     * Usage in <code>processMessage()</code>:
37
     *
38
     *     $sendMessage($this->local[$this->language]["Hello_Msg"]);
39
     *
40
     * @{
41
     */
42
43
    /** \brief (<i>Internal</i>)Store the localizated strings. */
44
    protected $local;
45
46
    /** \brief Directory where there are the localization files. */
47
    protected $localization_dir = './localization';
48
49
    /**
50
     * \brief (<i>Internal</i>)Load a localization file into the localized strings array.
51
     * @param string $lang Language to load.
52
     * @param string $dir Directory in which there are the JSON files.
53
     * @return bool True if loaded.
54
     */
55
    protected function loadSingleLanguage(string $lang = 'en', string $dir = './localization') : bool
56
    {
57
        // Name of the file
58
        $filename = "$dir/$lang";
59
60
        // If this language isn't already set
61
        if (!isset($this->local[$lang])) {
62
            // and the file exists
63
            if (file_exists($filename)) {
64
                // Load localization in memory
65
                $this->local[$lang] = json_decode(file_get_contents($filename), true);
66
67
                // We loaded it
68
                return true;
69
            }
70
            // The file doens't exists
71
            return false;
72
        }
73
74
        // The language is already set
75
        return true;
76
    }
77
78
    /**
79
     * \brief Load all localization files (JSON-serialized) from a folder and set them in $local variable.
80
     * \details Save all localization files, saved as json format, from a directory and put the contents in $local variable.
81
     * Each file will be saved into $local with the first two letters of the filename as the index.
82
     * @param string $dir Directory where the localization files are saved.
83
     * @return bool True if the directory could be opened without errors.
84
     */
85
    public function loadAllLocalizations(string $dir = './localization') : bool
86
    {
87
        // Open directory
88
        if ($handle = opendir($dir)) {
89
            // Iterate over all files
90
            while (false !== ($file = readdir($handle))) {
91
                // If the file is a JSON data file
92
                if (strlen($file) > 6 && substr($file, -5) === '.json') {
93
                    try {
94
                        // Add the contents of the file to the $local variable, after deserializng it from JSON format
95
                        // The contents will be added with the 2 letter of the file as the index
96
                        $this->local[substr($file, 0, 2)] = json_decode(file_get_contents("$dir/$file"), true);
97
                    } catch (BotException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Localization\BotException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
98
                        echo $e->getMessage();
99
                    }
100
                }
101
            }
102
            return true;
103
        }
104
        return false;
105
    }
106
107
    /**
108
     * \brief Load localization for current language and mode.
109
     * \details This method will load only the current user/group localization file if the bot is using webhook, all files otherwise.
110
     * @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).
111
     * @return bool True if the localization has been loaded or it is already loaded.
112
     */
113
    public function loadCurrentLocalization(string $dir = '') : bool
114
    {
115
        // If no dir has been given
116
        if (!isset($dir) || $dir === '') {
117
            // The dir is the default one
118
            $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...
119
        }
120
121
        // If the language of the user is already set in the array containing localizated strings
122
        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...
123
            // Is the bot using webhook?
124
            if (isset($this->_is_webhook)) {
125
                return $this->loadSingleLanguage($this->localization_dir);
126
            } else {
127
                return $this->loadAllLocalizations($this->localization_dir);
128
            }
129
        }
130
131
        return false;
132
    }
133
134
    /**
135
     * \brief Set location of localization files.
136
     * @param string $dir Directory where the files are stored.
137
     */
138
    public function setLocalizationDir(string $dir)
139
    {
140
        $this->localization_dir = $dir;
141
    }
142
143
    /** @} */
144
}
145