Passed
Pull Request — master (#13)
by Michal
01:38
created

BingTranslator::translate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 1
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Efabrica\TranslationsAutomatization\Translator;
4
5
use GuzzleHttp\Client;
6
7
class BingTranslator implements TranslatorInterface
8
{
9
    private $from;
10
11
    private $to;
12
13 8
    public function __construct(string $from, string $to)
14
    {
15 8
        $this->from = $from;
16 8
        $this->to = $to;
17 8
    }
18
19 4
    public function translate(array $strings): array
20
    {
21 4
        $guzzleClient = new Client();
22
        $options = [
23
            'form_params' => [
24 4
                'text' => implode(' | ', $strings),
25 4
                'from' => $this->from,
26 4
                'to' => $this->to,
27
            ]
28
        ];
29 4
        $request = $guzzleClient->request('POST', 'https://www.bing.com/ttranslate', $options);
30
31 4
        $newStrings = [];
32 4
        $response = json_decode((string) $request->getBody(), true);
33 4
        if ($response['statusCode'] === 200) {
34 4
            $newStrings = explode(' | ', $response['translationResponse']);
35
        }
36 4
        return array_combine($strings, $newStrings);
37
    }
38
}
39