Completed
Push — master ( 216072...caf6f7 )
by Team eFabrica
02:21
created

BingTranslateTokenModifier::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Efabrica\TranslationsAutomatization\TokenModifier;
4
5
use Efabrica\TranslationsAutomatization\Tokenizer\TokenCollection;
6
use GuzzleHttp\Client;
7
8
class BingTranslateTokenModifier implements TokenModifierInterface
9
{
10
    private $from;
11
12
    private $to;
13
14 4
    public function __construct(string $from, string $to)
15
    {
16 4
        $this->from = $from;
17 4
        $this->to = $to;
18 4
    }
19
20 4
    public function modifyAll(TokenCollection $tokenCollection): TokenCollection
21
    {
22 4
        $oldKeys = [];
23 4
        foreach ($tokenCollection->getTokens() as $token) {
24 2
            $oldKeys[] = $token->getTranslationKey();
25
        }
26
27 4
        if (empty($oldKeys)) {
28 2
            return $tokenCollection;
29
        }
30
31 2
        $guzzleClient = new Client();
32
        $options = [
33
            'form_params' => [
34 2
                'text' => implode(' | ', $oldKeys),
35 2
                'from' => $this->from,
36 2
                'to' => $this->to,
37
            ]
38
        ];
39 2
        $request = $guzzleClient->request('POST', 'https://www.bing.com/ttranslate', $options);
40
41 2
        $newKeys = [];
42 2
        $response = json_decode((string) $request->getBody(), true);
43 2
        if ($response['statusCode'] === 200) {
44 2
            $newKeys = explode(' | ', $response['translationResponse']);
45
        }
46 2
        $oldToNewKeys = array_combine($oldKeys, $newKeys);
47
48 2
        foreach ($tokenCollection->getTokens() as $token) {
49 2
            if (isset($oldToNewKeys[$token->getTranslationKey()])) {
50 2
                $token->changeTranslationKey($oldToNewKeys[$token->getTranslationKey()]);
51
            }
52
        }
53
54 2
        return $tokenCollection;
55
    }
56
}
57