BingTranslator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 4
eloc 20
c 2
b 1
f 0
dl 0
loc 37
ccs 17
cts 17
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A translate() 0 22 3
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
    private $chunkSize;
14
15 8
    public function __construct(string $from, string $to, int $chunkSize = 100)
16
    {
17 8
        $this->from = $from;
18 8
        $this->to = $to;
19 8
        $this->chunkSize = $chunkSize;
20 8
    }
21
22 4
    public function translate(array $texts): array
23
    {
24 4
        $newTexts = [];
25
26
        // TODO change chunk size to real character count limit (https://social.microsoft.com/Forums/en-US/abf2a48f-d8c7-41db-a1fa-00066e7040f4/limits-in-request-to-bing-translator-api?forum=translator)
27 4
        foreach (array_chunk($texts, $this->chunkSize) as $strings) {
28 4
            $guzzleClient = new Client();
29
            $options = [
30
                'form_params' => [
31 4
                    'text' => implode(' | ', $strings),
32 4
                    'fromLang' => $this->from,
33 4
                    'to' => $this->to,
34
                ]
35
            ];
36 4
            $request = $guzzleClient->request('POST', 'https://www.bing.com/ttranslatev3', $options);
37
38 4
            $response = json_decode((string) $request->getBody(), true);
39 4
            if ($request->getStatusCode() === 200) {
40 4
                $newTexts = array_merge($newTexts, array_map('trim', explode('|', $response[0]['translations'][0]['text'])));
41
            }
42
        }
43 4
        return array_combine($texts, $newTexts);
44
    }
45
}
46