Completed
Push — master ( 4e6963...479a33 )
by Benjamin
15s
created

SimpleGoogleTranslator::setSource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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
19 18
    public function setSource(string $source)
20
    {
21 18
        $this->source = $source;
22
23 18
        $this->translator->setSource($source);
24
25 18
        return $this;
26
    }
27
28
    public function setTarget(string $target)
29
    {
30
        $this->target = $target;
31
32
        $this->translator->setTarget($target);
33
34
        return $this;
35
    }
36
37
    public function translate(string $string) : string
38
    {
39
        try {
40
            sleep(random_int(1, 3));
41
42
            return $this->translator->translate($string);
43
        } catch (\Throwable $th) {
44
            if ($th->getMessage() === 'Return value of Stichoza\GoogleTranslate\GoogleTranslate::translate() must be of the type string, null returned') {
45
                throw LanguageCodeNotExist::throw($this->source, $this->target);
46
            }
47
        }
48
    }
49
}
50