translation::__()   B
last analyzed

Complexity

Conditions 9
Paths 4

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 30
c 0
b 0
f 0
rs 8.0555
cc 9
nc 4
nop 3
1
<?php
2
3
/**
4
 * © 2018 - Phoponent
5
 * Author: Nicolas Choquet
6
 * Email: [email protected]
7
 * LICENSE GPL ( GNU General Public License )
8
 */
9
10
namespace phoponent\framework\service;
11
12
use phoponent\framework\traits\service;
13
require_once __DIR__.'../../../external_libs/google-translate-php/vendor/autoload.php';
14
15
use Stichoza\GoogleTranslate\TranslateClient;
16
17
class translation {
18
	use service;
19
	private static $base_url = 'http://translate.google.cn/translate_a/single';
20
21
    /**
22
     * @param string|array $text
23
     * @param array $array
24
     * @param string $lang
25
     * @return string|array
26
     * @throws \Exception
27
     */
28
	public static function __($text, $array = [], $lang = 'en') {
29
		$translate_object = new TranslateClient();
30
		$translate_object->setUrlBase(self::$base_url);
31
		$translate_object->setTarget($lang);
32
		if(gettype($text) === 'array') {
33
			$translated = [];
34
			foreach ($text as $item) {
35
				$translated[] = $translate_object->translate($item);
36
			}
37
			if(!empty($array)) {
38
				foreach ($text as $text_id => $item) {
39
					if(isset($array[$text_id])) {
40
						foreach ($array[$text_id] as $id => $value) {
41
							$id         = $id+1;
42
							$translated[$text_id] = str_replace(["\$ {$id}", "\${$id}"], $value, $translated[$text_id]);
43
						}
44
					}
45
				}
46
			}
47
		}
48
		else {
49
			$translated = $translate_object->translate($text);
50
			if(!empty($array)) {
51
				foreach ($array as $id => $value) {
52
					$id = $id+1;
53
					$translated = str_replace(["\$ {$id}", "\${$id}"], $value, $translated);
54
				}
55
			}
56
		}
57
		return $translated;
58
	}
59
}