Completed
Push — master ( 86c869...cf203c )
by Aitor Riba
01:44
created

Translation::Save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
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 $translation;
15
    public $translator;
16
    public $string;
17
    public $debug;
18
    public $from;
19
    public $to;
20
    public $save;
21
22
    /**
23
     * Setup default values.
24
     *
25
     * @param string $string
26
     */
27
    public function __construct($string)
28
    {
29
        $this->translator = config('laralang.default.translator');
30
        $this->debug = config('laralang.default.debug');
31
        $this->save = config('laralang.default.autosave');
32
        $this->from = config('laralang.default.from_lang');
33
        $this->to = config('laralang.default.to_lang');
34
        $this->string = $string;
35
        $this->translation = $string;
36
37
38
        // Checking whether from_lang or to_lang are set as app_locale.
39
40
        if ($this->from == 'app_locale') {
41
            $this->from = App::getLocale();
42
        }
43
44
        if ($this->to == 'app_locale') {
45
            $this->to = App::getLocale();
46
        }
47
    }
48
49
    /**
50
     * Setup debug value.
51
     *
52
     * @param bool $debug
53
     */
54
    public function setDebug($debug)
55
    {
56
        $this->debug = $debug;
57
58
        return $this;
59
    }
60
61
    /**
62
     * Setup fromLang value.
63
     *
64
     * @param string $lang
65
     */
66
    public function setFrom($lang)
67
    {
68
        $this->from = $lang;
69
70
        return $this;
71
    }
72
73
    /**
74
     * Setup tolang value.
75
     *
76
     * @param string $lang
77
     */
78
    public function setTo($lang)
79
    {
80
        $this->to = $lang;
81
82
        return $this;
83
    }
84
85
    /**
86
     * Setup translator.
87
     *
88
     * @param string $translator
89
     */
90
    public function setTranslator($translator)
91
    {
92
        $this->translator = $translator;
93
94
        return $this;
95
    }
96
97
    /**
98
     * Setup save option.
99
     *
100
     * @param bool $save
101
     */
102
    public function Save($save)
103
    {
104
        $this->save = $save;
105
106
        return $this;
107
    }
108
109
110
    private function exists()
111
    {
112
        $existing = DB_Translation::where('string', '=', $this->string)
113
        ->where('from_lang', '=', $this->from)
114
        ->where('to_lang', '=', $this->to)
115
        ->where('translator', '=', $this->translator)->get();
116
117
        if (count($existing) == 0) {
118
            return false;
119
        }
120
        if ($this->debug === true) {
121
            $this->translation = "<font style='color:#00CC00;'>Translation loaded from DB</font>";
122
        } else {
123
            $this->translation = $existing[0]->translation;
124
        }
125
126
        return true;
127
    }
128
129
    /**
130
     * Function to save translations to DB.
131
     */
132
    private function checkSave()
133
    {
134
        if ($this->save === true){
135
            $trans = new DB_Translation();
136
            $trans->string = $this->string;
137
            $trans->from_lang = $this->from;
138
            $trans->to_lang = $this->to;
139
            $trans->translator = $this->translator;
140
            $trans->translation = $this->translation;
141
            $trans->save();
142
143
            // Checking debug setting to determinate how to output translation
144
145
            if ($this->debug === true) {
146
                $this->translation = "<font style='color:#00CC00;'> Translation saved on DB </font>";
147
            }
148
        } else {
149
            if ($this->debug === true) {
150
                $this->translation = "<font style='color:orange;'> Translation not saved on DB </font>";
151
            }
152
        }
153
    }
154
155
    /*
156
    * This fuction is called when host is down, and it would set translation if debug is true
157
    *
158
    */
159
    private function hostDown()
160
    {
161
        if ($this->debug === true) {
162
            $this->translation = "<font style='color:red;'>$this->translator host is down</font>";
163
        }
164
    }
165
166
    /**
167
     * Main function of the class.
168
     *
169
     * Check what translator must select.
170
     */
171
    private function run()
172
    {
173
174
        // Return the value if the language is the same.
175
176
        if ($this->from == $this->to) {
177
            if ($this->debug === true) {
178
                $this->translation = "<font style='color:orange;'>Same in <> out languge</font>";
179
            }
180
181
            return;
182
        }
183
184
185
        if ($this->exists() === true) {
186
            return;
187
        }
188
189
        $available_transoltors = ['apertium', 'mymemory'];
190
191
        // Checks available translators.
192
193
        if (! in_array($this->translator, $available_transoltors)) {
194
            if ($this->debug === true) {
195
                $this->translation = "<font style='color:red;'>Not suported translator: ".$this->translator.'</font>';
196
            }
197
198
            return;
199
        }
200
201
        if ($this->translator == 'apertium') {
202
            return $this->apertiumTrans();
203
        } elseif ($this->translator == 'mymemory') {
204
            return $this->mymemoryTrans();
205
        }
206
    }
207
208
     /**
209
      * Get translation from mymemory API.
210
      */
211
     private function mymemoryTrans()
212
     {
213
         // Check if it can be translated from online sources.
214
215
         $host = 'api.mymemory.translated.net';
216
         if ($socket = @fsockopen($host, 80, $errno, $errstr, 30)) {
217
218
             // Host online
219
             $urlString = urlencode($this->string);
220
             $url = "http://$host/get?q=$urlString&langpair=$this->from%7C$this->to";
221
             $json = file_get_contents($url);
222
             $data = json_decode($json);
223
224
             // Checking response status
225
226
             if ($data->responseStatus != 200) {
227
                 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...
228
                     $details = $data->responseDetails;
229
                     if ($data->responseStatus == 403) {
230
                         $details = ($data->responseDetails);
231
                     }
232
                     $this->translation = "<font style='color:red;'>Error ".$data->responseStatus.': '.$details.'</font>';
233
                 }
234
235
                 return;
236
             }
237
238
239
             $transObtained = $data->responseData->translatedText;
240
241
             $this->translation = ucfirst(strtolower(trim($transObtained)));
242
243
             $this->checkSave();
244
245
             fclose($socket);
246
             return;
247
248
         } else {
249
250
             //host offline
251
             $this->hostDown();
252
         }
253
     }
254
255
    /**
256
     * Get translation from apertium API.
257
     */
258
    private function apertiumTrans()
259
    {
260
        // Check if it can be translated from online sources.
261
262
        $host = 'api.apertium.org';
263
        if ($socket = @fsockopen($host, 80, $errno, $errstr, 30)) {
264
265
            // Host online
266
267
            $urlString = urlencode($this->string);
268
            $url = "http://$host/json/translate?q=$urlString&langpair=$this->from%7C$this->to";
269
            $json = file_get_contents($url);
270
            $data = json_decode($json);
271
272
            // Checking response status
273
274
            if ($data->responseStatus != 200) {
275
                if ($this->debug === true) {
276
                    $this->translation = "<font style='color:red;'>Error ".$data->responseStatus.': '.$data->responseDetails.'</font>';
277
                }
278
279
                return;
280
            }
281
282
            $transObtained = $data->responseData->translatedText;
283
284
285
            $this->translation = ucfirst(strtolower(trim(str_replace('*', ' ', $transObtained))));
286
287
288
            // Checking debug setting to determinate how to output translation
289
290
            if ($this->debug === true) {
291
                $errors = '';
292
                $words = explode(' ', $transObtained);
293
                foreach ($words as $word) {
294
                    if ($word != '') {
295
                        if ($word[0] == '*') {
296
                            $errors = $errors.substr($word, 1).', ';
297
                        }
298
                    }
299
                }
300
301
                if ($errors == '') {
302
                    $this->translation = "<font style='color:#00CC00;'>".$this->translation.'</font>';
303
                } else {
304
                    $this->translation = "<font style='color:orange;'>Unknoun words: ".substr($errors, 0, -2).'</font>';
305
                }
306
            }
307
308
            $this->checkSave();
309
310
            fclose($socket);
311
312
            return;
313
        } else {
314
            //host offline
315
            $this->hostDown();
316
        }
317
    }
318
319
    /*
320
     * This fuction is called by trans() function of Fadade Laralang
321
     * It would call run() function of this class and returns the translation
322
     *
323
     */
324
    public function __toString()
325
    {
326
        $this->run();
327
328
        return $this->translation;
329
    }
330
}
331