GoogleFreeTranslator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
eloc 20
c 1
b 0
f 1
dl 0
loc 39
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A translate() 0 24 3
1
<?php
2
3
namespace Efabrica\TranslationsAutomatization\Translator;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Psr7\Stream;
7
8
class GoogleFreeTranslator implements TranslatorInterface
9
{
10
    private $from;
11
12
    private $to;
13
14
    private $chunkSize;
15
16
    public function __construct(string $from, string $to, int $chunkSize = 100)
17
    {
18
        $this->from = $from;
19
        $this->to = $to;
20
        $this->chunkSize = $chunkSize;
21
    }
22
23
    public function translate(array $texts): array
24
    {
25
        $newTexts = [];
26
27
        foreach (array_chunk($texts, $this->chunkSize) as $strings) {
28
29
            $guzzleClient = new Client(['headers' => ['content-type' => 'application/x-www-form-urlencoded']]);
30
            $options = [
31
                'form_params' => [
32
                    'sl' => $this->from,
33
                    'tl' => $this->to,
34
                    'q' => implode('|', $strings),
35
                ]
36
37
            ];
38
            $request = $guzzleClient->request('POST', 'https://clients5.google.com/translate_a/t?client=dict-chrome-ex', $options);
39
40
            $response = json_decode((string) $request->getBody(), true);
41
42
            if ($request->getStatusCode() === 200) {
43
                $newTexts = array_merge($newTexts, array_map('trim', explode('|', $response['sentences'][0]['trans'])));
44
            }
45
        }
46
        return array_combine($texts, $newTexts);
47
    }
48
}
49