Completed
Push — master ( 723f41...76df68 )
by Aitor Riba
01:58
created

Translation::mymemoryTrans()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 49
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 8.5906
c 0
b 0
f 0
cc 6
eloc 23
nc 6
nop 0
1
<?php
2
3
namespace Aitor24\Laralang;
4
5
use Aitor24\Laralang\Models\DB_Translation;
6
use App;
7
use Illuminate\Support\Facades\DB;
8
9
class Translation
10
{
11
    /**
12
     * Setup public vars.
13
     */
14
    public $translator;
15
    public $translation;
16
    public $string;
17
    public $debug;
18
    public $from;
19
    public $to;
20
21
    /**
22
     * Setup default values.
23
     *
24
     * @param string $string
25
     */
26
    public function __construct($string)
27
    {
28
        $this->translator = config('laralang.default.translator');
29
        $this->debug = config('laralang.default.debug');
30
        $this->from = config('laralang.default.from_lang');
31
        $this->to = config('laralang.default.to_lang');
32
        $this->string = $string;
33
        $this->translation = $string;
34
35
36
        // Checking whether from_lang or to_lang are set as app_locale.
37
38
        if ($this->from == 'app_locale') {
39
            $this->from = App::getLocale();
40
        }
41
42
        if ($this->to == 'app_locale') {
43
            $this->to = App::getLocale();
44
        }
45
    }
46
47
    /**
48
     * Setup debug value.
49
     *
50
     * @param bool $debug
51
     */
52
    public function setDebug($debug)
53
    {
54
        $this->debug = $debug;
55
56
        return $this;
57
    }
58
59
    /**
60
     * Setup fromLang value.
61
     *
62
     * @param string $lang
63
     */
64
    public function setFrom($lang)
65
    {
66
        $this->from = $lang;
67
68
        return $this;
69
    }
70
71
    /**
72
     * Setup tolang value.
73
     *
74
     * @param string $lang
75
     */
76
    public function setTo($lang)
77
    {
78
        $this->to = $lang;
79
80
        return $this;
81
    }
82
83
    /**
84
     * Setup translator.
85
     *
86
     * @param string $translator
87
     */
88
    public function setTranslator($translator)
89
    {
90
        $this->translator = $translator;
91
92
        return $this;
93
    }
94
95
    private function exists()
96
    {
97
        $existing = DB_Translation::where('string', '=', $this->string)
98
        ->where('from_lang', '=', $this->from)
99
        ->where('to_lang', '=', $this->to)
100
        ->where('translator', '=', $this->translator)->get();
101
102
        if (count($existing) == 0) {
103
            return false;
104
        }
105
        if ($this->debug === true) {
106
            $this->translation = "<font style='color:#00CC00;'>Loaded correclty from you DB</font>";
107
        } else {
108
            $this->translation = $existing[0]->translation;
109
        }
110
111
        return true;
112
    }
113
114
    /**
115
     * Function to save translations to DB.
116
     */
117
    private function save()
118
    {
119
        $trans = new DB_Translation();
120
        $trans = new DB_Translation();
121
        $trans->string = $this->string;
122
        $trans->from_lang = $this->from;
123
        $trans->to_lang = $this->to;
124
        $trans->translator = $this->translator;
125
        $trans->translation = $this->translation;
126
        $trans->save();
127
    }
128
129
    /**
130
     * Main function of the class.
131
     *
132
     * Check what translator must select.
133
     */
134
    private function run()
135
    {
136
137
        // Return the value if the language is the same.
138
139
        if ($this->from == $this->to) {
140
            if ($this->debug === true) {
141
                $this->translation = "<font style='color:orange;'>Same in <> out languge</font>";
142
            }
143
144
            return;
145
        }
146
147
148
        if ($this->exists() === true) {
149
            return;
150
        }
151
152
        $available_transoltors = ['apertium', 'mymemory'];
153
154
        // Checks available translators.
155
156
        if (in_array($this->translator, $available_transoltors) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
157
            if ($this->debug === true) {
158
                $this->translation = "<font style='color:red;'>Not suported translator: ".$this->translator.'</font>';
159
            }
160
161
            return;
162
        }
163
164
        if ($this->translator == 'apertium') {
165
            return $this->apertiumTrans();
166
        } elseif ($this->translator == 'mymemory') {
167
            return $this->mymemoryTrans();
168
        }
169
    }
170
171
     /**
172
      * Get translation from mymemory API.
173
      */
174
     private function mymemoryTrans()
175
     {
176
         // Check if it can be translated from online sources.
177
178
         $host = 'api.mymemory.translated.net';
179
         if ($socket = @fsockopen($host, 80, $errno, $errstr, 30)) {
0 ignored issues
show
Unused Code introduced by
$socket 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...
180
181
             // Host online
182
             $urlString = urlencode($this->string);
183
             $url = "http://$host/get?q=$urlString&langpair=$this->from%7C$this->to";
184
             $json = file_get_contents($url);
185
             $data = json_decode($json);
186
187
             // Checking response status
188
189
             if ($data->responseStatus != 200) {
190
                 if ($this->debug == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
191
                     $details = $data->responseDetails;
192
                     if ($data->responseStatus == 403) {
193
                         $details = ($data->responseDetails);
194
                     }
195
                     $this->translation = "<font style='color:red;'>Error ".$data->responseStatus.': '.$details.'</font>';
196
                 }
197
198
                 return;
199
             }
200
201
202
             $transObtained = $data->responseData->translatedText;
203
204
             $this->translation = ucfirst(strtolower(trim($transObtained)));
205
206
             $this->save();
207
208
             // Checking debug setting to determinate how to output translation
209
210
             if ($this->debug === true) {
211
                 $this->translation = "<font style='color:#00CC00;'>".$this->translation.'</font>';
212
             }
213
214
215
             return;
216
             fclose($socket);
0 ignored issues
show
Unused Code introduced by
fclose($socket); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
217
         } else {
218
219
             //host offline
220
             $this->hostDown();
221
         }
222
     }
223
224
    /**
225
     * Get translation from apertium API.
226
     */
227
    private function apertiumTrans()
228
    {
229
        // Check if it can be translated from online sources.
230
231
        $host = 'api.apertium.org';
232
        if ($socket = @fsockopen($host, 80, $errno, $errstr, 30)) {
233
234
            // Host online
235
236
            $urlString = urlencode($this->string);
237
            $url = "http://$host/json/translate?q=$urlString&langpair=$this->from%7C$this->to";
238
            $json = file_get_contents($url);
239
            $data = json_decode($json);
240
241
            // Checking response status
242
243
            if ($data->responseStatus != 200) {
244
                if ($this->debug === true) {
245
                    $this->translation = "<font style='color:red;'>Error ".$data->responseStatus.': '.$data->responseDetails.'</font>';
246
                }
247
248
                return;
249
            }
250
251
            $transObtained = $data->responseData->translatedText;
252
253
254
            $this->translation = ucfirst(strtolower(trim(str_replace('*', ' ', $transObtained))));
255
256
257
            // Checking debug setting to determinate how to output translation
258
259
            if ($this->debug === true) {
260
                $errors = '';
261
                $words = explode(' ', $transObtained);
262
                foreach ($words as $word) {
263
                    if ($word != '') {
264
                        if ($word[0] == '*') {
265
                            $errors = $errors.substr($word, 1).', ';
266
                        }
267
                    }
268
                }
269
270
                if ($errors == '') {
271
                    $this->translation = "<font style='color:#00CC00;'>".$this->translation.'</font>';
272
                } else {
273
                    $this->translation = "<font style='color:orange;'>Unknoun words: ".substr($errors, 0, -2).'</font>';
274
                }
275
            }
276
277
            fclose($socket);
278
279
            return;
280
        } else {
281
            //host offline
282
            $this->hostDown();
283
        }
284
    }
285
286
    /*
287
     * This fuction is called when host is down, and it would set translation if debug is true
288
     *
289
     */
290
    private function hostDown()
291
    {
292
        if ($this->debug === true) {
293
            $this->translation = "<font style='color:red;'>$this->translator host is down</font>";
294
        }
295
    }
296
297
    /*
298
     * This fuction is called by trans() function of Fadade Laralang
299
     * It would call run() function of this class and returns the translation
300
     *
301
     */
302
    public function __toString()
303
    {
304
        $this->run();
305
306
        return $this->translation;
307
    }
308
}
309