Conditions | 5 |
Paths | 12 |
Total Lines | 56 |
Code Lines | 15 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
40 | public static function google_translate($sourceText, $targetLang = null, $sourceLang = null) |
||
41 | { |
||
42 | if (!$sourceLang) { |
||
43 | $sourceLang = 'auto'; |
||
44 | } |
||
45 | if (!$targetLang) { |
||
46 | $targetLang = 'en'; |
||
47 | } |
||
48 | |||
49 | $targetLang = substr($targetLang, 0, 2); |
||
50 | |||
51 | $url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" |
||
52 | . $sourceLang . "&tl=" . $targetLang . "&dt=t&q=" . urlencode($sourceText); |
||
53 | |||
54 | $result = file_get_contents($url); |
||
55 | if (!$result) { |
||
56 | throw new Exception("Failed to fetch content from $url"); |
||
57 | } |
||
58 | $data = json_decode($result, true); |
||
59 | if (!$data) { |
||
60 | throw new Exception("Failed to decode json : " . json_last_error_msg()); |
||
61 | } |
||
62 | |||
63 | // array:9 [▼ |
||
64 | // 0 => array:1 [▼ |
||
65 | // 0 => array:5 [▼ |
||
66 | // 0 => "TargetTextHere" |
||
67 | // 1 => "SourceTextHere" |
||
68 | // 2 => null |
||
69 | // 3 => null |
||
70 | // 4 => 1 |
||
71 | // ] |
||
72 | // ] |
||
73 | // 1 => null |
||
74 | // 2 => "en" |
||
75 | // 3 => null |
||
76 | // 4 => null |
||
77 | // 5 => null |
||
78 | // 6 => 1.0 |
||
79 | // 7 => [] |
||
80 | // 8 => array:4 [▼ |
||
81 | // 0 => array:1 [▼ |
||
82 | // 0 => "en" |
||
83 | // ] |
||
84 | // 1 => null |
||
85 | // 2 => array:1 [▼ |
||
86 | // 0 => 1.0 |
||
87 | // ] |
||
88 | // 3 => array:1 [▼ |
||
89 | // 0 => "en" |
||
90 | // ] |
||
91 | // ] |
||
92 | |||
93 | $translatedText = $data[0][0][0]; |
||
94 | |||
95 | return $translatedText; |
||
96 | } |
||
145 |