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

BingTranslateTokenModifier   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
B modifyAll() 0 35 6
A __construct() 0 4 1
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