| 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 |
||
| 39 | public static function google_translate($sourceText, $targetLang = null, $sourceLang = null) |
||
| 40 | { |
||
| 41 | if (!$sourceLang) { |
||
| 42 | $sourceLang = 'auto'; |
||
| 43 | } |
||
| 44 | if (!$targetLang) { |
||
| 45 | $targetLang = 'en'; |
||
| 46 | } |
||
| 47 | |||
| 48 | $targetLang = substr($targetLang, 0, 2); |
||
| 49 | |||
| 50 | $url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" |
||
| 51 | . $sourceLang . "&tl=" . $targetLang . "&dt=t&q=" . urlencode($sourceText); |
||
| 52 | |||
| 53 | $result = file_get_contents($url); |
||
| 54 | if (!$result) { |
||
| 55 | throw new Exception("Failed to fetch content from $url"); |
||
| 56 | } |
||
| 57 | $data = json_decode($result, true); |
||
| 58 | if (!$data) { |
||
| 59 | throw new Exception("Failed to decode json : " . json_last_error_msg()); |
||
| 60 | } |
||
| 61 | |||
| 62 | // array:9 [▼ |
||
| 63 | // 0 => array:1 [▼ |
||
| 64 | // 0 => array:5 [▼ |
||
| 65 | // 0 => "TargetTextHere" |
||
| 66 | // 1 => "SourceTextHere" |
||
| 67 | // 2 => null |
||
| 68 | // 3 => null |
||
| 69 | // 4 => 1 |
||
| 70 | // ] |
||
| 71 | // ] |
||
| 72 | // 1 => null |
||
| 73 | // 2 => "en" |
||
| 74 | // 3 => null |
||
| 75 | // 4 => null |
||
| 76 | // 5 => null |
||
| 77 | // 6 => 1.0 |
||
| 78 | // 7 => [] |
||
| 79 | // 8 => array:4 [▼ |
||
| 80 | // 0 => array:1 [▼ |
||
| 81 | // 0 => "en" |
||
| 82 | // ] |
||
| 83 | // 1 => null |
||
| 84 | // 2 => array:1 [▼ |
||
| 85 | // 0 => 1.0 |
||
| 86 | // ] |
||
| 87 | // 3 => array:1 [▼ |
||
| 88 | // 0 => "en" |
||
| 89 | // ] |
||
| 90 | // ] |
||
| 91 | |||
| 92 | $translatedText = $data[0][0][0]; |
||
| 93 | |||
| 94 | return $translatedText; |
||
| 95 | } |
||
| 144 |