Passed
Pull Request — master (#5)
by
unknown
02:57
created

Translation   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 29.17%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 176
ccs 14
cts 48
cp 0.2917
rs 10
wmc 22
lcom 1
cbo 3

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A translate() 0 4 1
A translug() 0 4 1
A getTranslatedText() 0 14 3
A getTranslation() 0 8 2
A getTranslatedTextFromResponse() 0 4 1
A getTranslateUrl() 0 6 1
A getTranslateUrlV2() 0 12 1
A isEnglish() 0 8 2
A removeSegment() 0 4 1
B getVersion() 0 18 8
1
<?php
2
3
namespace JellyBool\Translug;
4
5
use GuzzleHttp\Client;
6
use JellyBool\Translug\Exceptions\TranslationErrorException;
7
8
/**
9
 * Class Translation.
10
 */
11
class Translation
12
{
13
    /**
14
     * Youdao api url.
15
     *
16
     * @var string
17
     */
18
    protected $api = 'http://fanyi.youdao.com/openapi.do?type=data&doctype=json&version=1.1&';
19
20
    /**
21
     * ai.youdao.com api url
22
     * @var string
23
     */
24
    protected $api_v2 = 'http://openapi.youdao.com/api?from=zh-CHS&to=EN&';
25
26
    /**
27
     * @var Client
28
     */
29
    protected $http;
30
31
    /**
32
     * @var array
33
     */
34
    protected $config = [];
35
36
    /**
37
     * Translation constructor.
38
     *
39
     * @param Client $http
40
     * @param array  $config
41
     */
42 5
    public function __construct(Client $http, array $config = [])
43
    {
44 5
        $this->http = $http;
45 5
        $this->config = $config;
46 5
    }
47
48
    /**
49
     * @param $text
50
     *
51
     * @return mixed
52
     */
53 3
    public function translate($text)
54
    {
55 3
        return $this->getTranslatedText($text);
56
    }
57
58
    /**
59
     * @param $text
60
     *
61
     * @return string
62
     */
63 1
    public function translug($text)
64
    {
65 1
        return str_slug($this->getTranslatedText($text));
66
    }
67
68
    /**
69
     * @param $text
70
     *
71
     * @return mixed
72
     */
73 4
    private function getTranslatedText($text)
74
    {
75 4
        if ($this->isEnglish($text)) {
76 4
            return $text;
77
        }
78
79
        $method = $this->getVersion() == 1 ? 'getTranslateUrl' : 'getTranslateUrlV2';
80
81
        $text = $this->removeSegment($text);
82
        $url = $this->$method($text);
83
        $response = $this->http->get($url);
84
85
        return $this->getTranslation(json_decode($response->getBody(), true));
86
    }
87
88
    /**
89
     * @param array $translateResponse
90
     *
91
     * @return mixed
92
     */
93
    private function getTranslation(array $translateResponse)
94
    {
95
        if ($translateResponse['errorCode'] == 0) {
96
            return $this->getTranslatedTextFromResponse($translateResponse);
97
        }
98
99
        throw new TranslationErrorException('Translate error, error_code : '.$translateResponse['errorCode'].'. Refer url: http://fanyi.youdao.com/openapi?path=data-mode');
100
    }
101
102
    /**
103
     * @param array $translateResponse
104
     *
105
     * @return mixed
106
     */
107
    private function getTranslatedTextFromResponse(array $translateResponse)
108
    {
109
        return $translateResponse['translation'][0];
110
    }
111
112
    /**
113
     * @param $text
114
     *
115
     * @return string
116
     */
117
    private function getTranslateUrl($text)
118
    {
119
        $query = http_build_query($this->config);
120
121
        return $this->api.$query.'&q='.urlencode($text);
122
    }
123
124
    /**
125
     * @param $text
126
     *
127
     * @return string
128
     */
129
    private function getTranslateUrlV2($text)
130
    {
131
        $key = $this->config['appKey'];
132
        $secret = $this->config['appSecret'];
133
134
        $salt = md5(time());
135
        $sign = md5($key . $text . $salt . $secret);
136
137
        $query = http_build_query(['salt' => $salt, 'sign' => $sign, 'appKey' => $key]);
138
139
        return $this->api_v2.$query.'&q='.urlencode($text);
140
    }
141
142
    /**
143
     * @param $text
144
     *
145
     * @return bool
146
     */
147 4
    private function isEnglish($text)
148
    {
149 4
        if (preg_match("/\p{Han}+/u", $text)) {
150
            return false;
151
        }
152
153 4
        return true;
154
    }
155
156
    /**
157
     * Remove segment #.
158
     *
159
     * @param $text
160
     *
161
     * @return mixed
162
     */
163
    private function removeSegment($text)
164
    {
165
        return str_replace('#', '', ltrim($text));
166
    }
167
168
    private function getVersion()
169
    {
170
        if (!empty($this->config)) {
171
            return !empty($this->config['keyfrom']) && !empty($this->config['key']) ? 1 : 2;
172
        }
173
174
        if (!empty(config('services.youdao.appKey')) && !empty(config('services.youdao.appSecret'))) {
175
            $this->config = ['appKey' => config('services.youdao.appKey'), 'appSecret' => config('services.youdao.appSecret')];
176
            return 2;
177
        }
178
179
        if (!empty(config('services.youdao.from')) && !empty(config('services.youdao.key'))) {
180
            $this->config = ['keyfrom' => config('services.youdao.from'), 'key' => config('services.youdao.key')];
181
            return 1;
182
        }
183
184
        throw new TranslationErrorException('Translate error, configuration error');
185
    }
186
}
187