· 4 years ago · Aug 03, 2021, 07:42 AM
1TTTController.php
2
3<?php
4
5namespace App\Http\Controllers;
6
7use Illuminate\Http\Request;
8
9class TTTController extends Controller {
10
11 private $toMessage;
12
13 private $googleAPIKey;
14
15 /**
16 * Create a new controller instance.
17 *
18 * @return void
19 */
20 public function __construct() {
21
22 $this->middleware('rosetTalkUser');
23 $this->toMessage = '';
24
25 // SET GOOGLE TRANSLATION API KEY.
26 $this->googleAPIKey = Config('constants.TTT.ENGINE.GOOGLE.API_KEY');
27
28 $this->JSONData = json_decode(file_get_contents(base_path('resources/languages.json')), true);
29 }
30
31 /**
32 * @return [file]
33 */
34 public function index() {
35
36 return view('TTTConverter');
37 }
38
39 /**
40 * @param Request [fromLang, toLang, fromMessage]
41 * @return [json] [toMessage]
42 */
43 public function TTTConvert(Request $request) {
44
45 $fromLangCode = isset($this->JSONData[$request->fromLang]) ?
46 $this->JSONData[$request->fromLang]['lang_code'] :
47 Config('constants.TTT.ERR_MSG.FROM_LANG_NOT_FOUND');
48
49 $toLangCode = isset($this->JSONData[$request->toLang]) ?
50 $this->JSONData[$request->toLang]['lang_code'] :
51 Config('constants.TTT.ERR_MSG.TO_LANG_NOT_FOUND');
52
53 // GOOGLE TRANSLATION.
54 $url = Config('constants.TTT.ENGINE.GOOGLE.TRANSLATE_URI') . $this->googleAPIKey
55 . '&q=' . rawurlencode($request->fromMessage)
56 . '&source=' . $fromLangCode
57 . '&target=' . $toLangCode;
58
59 $handle = curl_init($url);
60 curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
61 $response = curl_exec($handle);
62 $responseDecoded = json_decode($response, true);
63 curl_close($handle);
64
65 // WHEN BOTH LANGUAGE INPUTS ARE IDENTICAL.
66 if ($fromLangCode!=$toLangCode) {
67 $this->toMessage .= htmlspecialchars_decode($responseDecoded['data']['translations'][0]['translatedText'], ENT_QUOTES);
68 } else {
69 $this->toMessage .= htmlspecialchars_decode($request->fromMessage, ENT_QUOTES);
70 }
71
72 $data = [
73 'toMessage' => $this->toMessage
74 ];
75
76 return response()->json($data);
77 }
78}
79