GoogleTranslator   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
wmc 3
eloc 19
c 2
b 0
f 2
dl 0
loc 44
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A translate() 0 17 2
1
<?php
2
3
namespace Efabrica\TranslationsAutomatization\Translator;
4
5
use Google\Client;
6
use Google\Cloud\Translate\V3\TranslationServiceClient;
7
8
class GoogleTranslator implements TranslatorInterface
9
{
10
    private TranslationServiceClient $translationServiceClient;
11
12
    private string $projectId;
13
14
    private string $languageFrom;
15
16
    private string $languageTo;
17
18
    public function __construct(
19
        string $projectId,
20
        string $credentialsFilePath,
21
        string $languageFrom,
22
        string $languageTo
23
    ) {
24
        $this->projectId = $projectId;
25
        $this->languageFrom = $languageFrom;
26
        $this->languageTo = $languageTo;
27
28
        // google credentials
29
        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credentialsFilePath);
30
31
        // cannot use service - before create must be authorized google credentials
32
        $this->translationServiceClient = new TranslationServiceClient();
33
    }
34
35
    public function translate(array $texts): array
36
    {
37
        $response = $this->translationServiceClient->translateText(
38
            $texts,
39
            $this->languageTo,
40
            TranslationServiceClient::locationName($this->projectId, 'global'),
41
            [
42
                'sourceLanguageCode' => $this->languageFrom,
43
            ]
44
        );
45
46
        $translations = [];
47
        foreach ($response->getTranslations() as $translation) {
48
            $translations[] = html_entity_decode($translation->getTranslatedText());
49
        }
50
51
        return array_combine($texts, $translations);
52
    }
53
}
54