SimpleGoogleTranslator::translate()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 7
cp 0
rs 9.7998
c 0
b 0
f 0
cc 3
nc 5
nop 1
crap 12
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