SimpleGoogleTranslator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 38.1%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 50
ccs 8
cts 21
cp 0.381
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A setSource() 0 8 1
A setTarget() 0 8 1
A translate() 0 14 3
1
<?php
2
3
namespace Ben182\AutoTranslate\Translators;
4
5
use Stichoza\GoogleTranslate\GoogleTranslate;
6
use Ben182\AutoTranslate\Exceptions\LanguageCodeNotExist;
7
8
class SimpleGoogleTranslator implements TranslatorInterface
9
{
10
    protected $translator;
11
    protected $source;
12
    protected $target;
13
14 18
    public function __construct()
15
    {
16 18
        $this->translator = new GoogleTranslate;
17
18 18
        if (config('auto-translate.simple_google_translator.proxy')) {
19
            $this->translator->setOptions([
20
                'proxy' => config('auto-translate.simple_google_translator.proxy'),
21
            ]);
22
        }
23 18
    }
24
25 18
    public function setSource(string $source)
26
    {
27 18
        $this->source = $source;
28
29 18
        $this->translator->setSource($source);
30
31 18
        return $this;
32
    }
33
34
    public function setTarget(string $target)
35
    {
36
        $this->target = $target;
37
38
        $this->translator->setTarget($target);
39
40
        return $this;
41
    }
42
43
    public function translate(string $string) : string
44
    {
45
        try {
46
            sleep(random_int(config('auto-translate.simple_google_translator.sleep_between_requests')[0], config('auto-translate.simple_google_translator.sleep_between_requests')[1]));
47
48
            return $this->translator->translate($string);
49
        } catch (\Throwable $th) {
50
            if ($th->getMessage() === 'Return value of Stichoza\GoogleTranslate\GoogleTranslate::translate() must be of the type string, null returned') {
51
                throw LanguageCodeNotExist::throw($this->source, $this->target);
52
            }
53
54
            throw $th;
55
        }
56
    }
57
}
58