Completed
Pull Request — master (#151)
by Alexander
04:33
created

DictionaryClient::getLanguages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 16
Ratio 100 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 16
loc 16
ccs 12
cts 12
cp 1
rs 9.4285
cc 2
eloc 10
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * Yandex PHP Library
4
 *
5
 * @copyright NIX Solutions Ltd.
6
 * @link https://github.com/nixsolutions/yandex-php-library
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Yandex\Dictionary;
13
14
use Yandex\Common\AbstractServiceClient;
15
use GuzzleHttp\Psr7\Response;
16
use Psr\Http\Message\UriInterface;
17
use GuzzleHttp\Exception\ClientException;
18
use Yandex\Common\Exception\ForbiddenException;
19
use Yandex\Dictionary\Exception\DictionaryException;
20
21
/**
22
 * Class DictionaryClient implements Yandex Dictionary protocol
23
 *
24
 * @category Yandex
25
 * @package  Dictionary
26
 *
27
 * @author   Nikolay Oleynikov <[email protected]>
28
 * @created  07.11.14 18:43
29
 */
30
class DictionaryClient extends AbstractServiceClient
31
{
32
    /**
33
     * @const
34
     */
35
    const FAMILY_FLAG = 0x0001;
36
37
    /**
38
     * @const
39
     */
40
    const MORPHO_FLAG = 0x0004;
41
42
    /**
43
     * @const
44
     */
45
    const POSITION_FILTER_FLAG = 0x0008;
46
47
    /**
48
     * @var
49
     */
50
    protected $apiKey;
51
52
    /**
53
     * @var string
54
     */
55
    protected $serviceDomain = 'dictionary.yandex.net';
56
57
    /**
58
     * @var
59
     */
60
    protected $uiLanguage = 'en';
61
62
    /**
63
     * @var
64
     */
65
    protected $translateFrom = 'en';
66
67
    /**
68
     * @var
69
     */
70
    protected $translateTo = 'en';
71
72
    /**
73
     * @var
74
     */
75
    protected $flags = 0;
76
77
    /**
78
     * @param string $apiKey API key
79
     */
80 20
    public function __construct($apiKey)
81
    {
82 20
        $this->setApiKey($apiKey);
83 20
    }
84
85
    /**
86
     * @param string $apiKey
87
     *
88
     * @return $this
89
     */
90 20
    public function setApiKey($apiKey)
91
    {
92 20
        $this->apiKey = $apiKey;
93
94 20
        return $this;
95
    }
96
97
    /**
98
     * @param boolean $enabled optional boolean
99
     *
100
     * @return $this
101
     */
102 2
    public function setFamilyFlag($enabled = true)
103
    {
104 2
        $this->setFlag(self::FAMILY_FLAG, $enabled);
105
106 2
        return $this;
107
    }
108
109
    /**
110
     * @param boolean $enabled optional boolean
111
     *
112
     * @return $this
113
     */
114 2
    public function setMorphoFlag($enabled = true)
115
    {
116 2
        $this->setFlag(self::MORPHO_FLAG, $enabled);
117
118 2
        return $this;
119
    }
120
121
    /**
122
     * @param boolean $enabled optional boolean
123
     *
124
     * @return $this
125
     */
126 2
    public function setPositionFilterFlag($enabled = true)
127
    {
128 2
        $this->setFlag(self::POSITION_FILTER_FLAG, $enabled);
129
130 2
        return $this;
131
    }
132
133
    /**
134
     * @return integer
135
     */
136 9
    public function getFlags()
137
    {
138 9
        return $this->flags;
139
    }
140
141
    /**
142
     * @param integer $flag
143
     * @param boolean $enabled optional boolean
144
     *
145
     * @return $this
146
     */
147 6
    public function setFlag($flag, $enabled = true)
148
    {
149 6
        if ($enabled) {
150 3
            $this->flags |= $flag;
151 3
        } else {
152 3
            $this->flags &= ~$flag;
153
        }
154
155 6
        return $this;
156
    }
157
158
    /**
159
     * @return string
160
     */
161 8
    public function getApiKey()
162
    {
163 8
        return $this->apiKey;
164
    }
165
166
    /**
167
     * @param string $uiLanguage
168
     *
169
     * @return $this
170
     */
171 2
    public function setUiLanguage($uiLanguage)
172
    {
173 2
        $this->uiLanguage = $uiLanguage;
174
175 2
        return $this;
176
    }
177
178
    /**
179
     * @return string
180
     */
181 5
    public function getUiLanguage()
182
    {
183 5
        return $this->uiLanguage;
184
    }
185
186
    /**
187
     * @param string $translateFrom
188
     *
189
     * @return $this
190
     */
191 5
    public function setTranslateFrom($translateFrom)
192
    {
193 5
        $this->translateFrom = $translateFrom;
194
195 5
        return $this;
196
    }
197
198
    /**
199
     * @return string
200
     */
201 2
    public function getTranslateFrom()
202
    {
203 2
        return $this->translateFrom;
204
    }
205
206
    /**
207
     * @param $translateTo
208
     *
209
     * @return $this
210
     */
211 5
    public function setTranslateTo($translateTo)
212
    {
213 5
        $this->translateTo = $translateTo;
214
215 5
        return $this;
216
    }
217
218
    /**
219
     * @return string
220
     */
221 2
    public function getTranslateTo()
222
    {
223 2
        return $this->translateTo;
224
    }
225
226
    /**
227
     * @return string
228
     */
229 3
    public function getLanguage()
230
    {
231 3
        return $this->translateFrom . '-' . $this->translateTo;
232
    }
233
234
    /**
235
     * @param string $text
236
     *
237
     * @return string
238
     */
239 3
    public function getLookupUrl($text)
240
    {
241 3
        $resource = 'api/v1/dicservice.json/lookup';
242 3
        $query = http_build_query(
243
            [
244 3
                'key' => $this->getApiKey(),
245 3
                'lang' => $this->getLanguage(),
246 3
                'ui' => $this->getUiLanguage(),
247 3
                'flags' => $this->getFlags(),
248
                'text' => $text
249 3
            ]
250 3
        );
251 3
        $url = $this->getServiceUrl($resource) . '?' . $query;
252
253 3
        return $url;
254
    }
255
256
    /**
257
     * @return string
258
     */
259 4
    public function getGetLanguagesUrl()
260
    {
261 4
        $resource = 'api/v1/dicservice.json/getLangs';
262 4
        $query = http_build_query(
263
            [
264 4
                'key' => $this->getApiKey()
265 4
            ]
266 4
        );
267 4
        $url = $this->getServiceUrl($resource) . '?' . $query;
268
269 4
        return $url;
270
    }
271
272
    /**
273
     * Looks up a text in the dictionary
274
     *
275
     * @param string $text
276
     *
277
     * @return array|bool
278
     *
279
     * @throws DictionaryException
280
     * @throws ForbiddenException
281
     */
282 3 View Code Duplication
    public function lookup($text)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
283
    {
284 3
        $url = $this->getLookupUrl($text);
285 3
        $response = $this->sendRequest(
286 3
            'GET',
287 3
            $url,
288
            [
289 3
                'version' => $this->serviceProtocolVersion
290 3
            ]
291 3
        );
292 3
        if ($response->getStatusCode() === 200) {
293 2
            $definitions = $this->parseLookupResponse($response);
294 2
            return $definitions;
295
        }
296 1
        return false;
297
    }
298
299
    /**
300
     * @return array|bool
301
     *
302
     * @throws DictionaryException
303
     * @throws ForbiddenException
304
     */
305 4 View Code Duplication
    public function getLanguages()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
306
    {
307 4
        $url = $this->getGetLanguagesUrl();
308 4
        $response = $this->sendRequest(
309 4
            'GET',
310 4
            $url,
311
            [
312 4
                'version' => $this->serviceProtocolVersion
313 4
            ]
314 4
        );
315 2
        if ($response->getStatusCode() === 200) {
316 1
            $languages = $this->parseGetLanguagesResponse($response);
317 1
            return $languages;
318
        }
319 1
        return false;
320
    }
321
322
    /**
323
     * @param Response $response
324
     *
325
     * @return array
326
     */
327 2
    protected function parseLookupResponse(Response $response)
328
    {
329 2
        $responseData = $response->getBody();
330 2
        $responseObject = json_decode($responseData);
331 2
        $definitionsData = $responseObject->def;
332 2
        $definitions = [];
333 2
        foreach ($definitionsData as $definitionData) {
334 2
            $definitions[] = new DictionaryDefinition($definitionData);
335 2
        }
336 2
        return $definitions;
337
    }
338
339
    /**
340
     * @param Response $response
341
     *
342
     * @return array
343
     */
344 1
    protected function parseGetLanguagesResponse(Response $response)
345
    {
346 1
        $responseBody = $response->getBody();
347 1
        $responseData = json_decode($responseBody);
348 1
        $languages = [];
349 1
        foreach ($responseData as $language) {
350 1
            $translation = explode('-', $language);
351 1
            $from = $translation[0];
352 1
            $to = $translation[1];
353 1
            $languages[] = [$from,$to];
354 1
        }
355 1
        return $languages;
356
    }
357
358
    /**
359
     * Sends a request
360
     *
361
     * @param string              $method  HTTP method
362
     * @param string|UriInterface $uri     URI object or string.
363
     * @param array               $options Request options to apply.
364
     *
365
     * @return Response
366
     *
367
     * @throws ForbiddenException
368
     * @throws DictionaryException
369
     */
370 7
    protected function sendRequest($method, $uri, array $options = [])
371
    {
372
        try {
373 7
            $response = $this->getClient()->request($method, $uri, $options);
374 7
        } catch (ClientException $ex) {
375 2
            $response = $ex->getResponse();
376 2
            $code = $response->getStatusCode();
377 2
            $message = $response->getReasonPhrase();
378
379 2
            if ($code === 403) {
380 1
                throw new ForbiddenException($message);
381
            }
382
383 1
            throw new DictionaryException(
384 1
                'Service responded with error code: "' . $code . '" and message: "' . $message . '"',
385
                $code
386 1
            );
387
        }
388
389 5
        return $response;
390
    }
391
}
392