Passed
Push — master ( d59e0a...db01b9 )
by Robin
02:53
created

GoogleTranslator::randomUserAgent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace TopviewDigital\TranslationHelper\Service;
4
5
use Campo\UserAgent;
6
use Stichoza\GoogleTranslate\GoogleTranslate;
7
use TopviewDigital\TranslationHelper\Interfaces\TranslatorInterface;
8
9
class GoogleTranslator implements TranslatorInterface
10
{
11
    protected $break = 0;
12
    protected $called = 0;
13
    protected $word;
14
    protected $source_locale = null;
15
    protected $target_locale;
16
17
    public function __construct()
18
    {
19
        $this->target_locale = config('app.locale');
20
    }
21
22
    public function word(string $word)
23
    {
24
        $this->word = $word;
25
        return $this;
26
    }
27
28
    public function targetLocale(string $target_locale)
29
    {
30
        $this->target_locale = $target_locale;
31
        return $this;
32
    }
33
34
    public function sourceLocale(string $source_locale)
35
    {
36
        $this->source_locale = $source_locale;
37
        return $this;
38
    }
39
40
41
    private function randomUserAgent()
42
    {
43
        sleep(1);
44
        $this->called++;
45
46
        return [
47
            'headers' => [
48
                'User-Agent' => UserAgent::random(),
49
            ],
50
        ];
51
    }
52
53
    public function translate()
54
    {
55
        $translated = '';
56
        $translator = new GoogleTranslate();
57
        while (empty($translated) && !empty($this->word)) {
58
            $this->called = 0;
59
            try {
60
                $translated = is_null($this->source_locale)
61
                    ? $translator
62
                    ->setOptions($this->randomUserAgent())
63
                    ->setSource()
64
                    ->setTarget($this->target_locale)
65
                    ->translate($this->word)
66
                    : $translator
67
                    ->setOptions($this->randomUserAgent())
68
                    ->setSource($this->source_locale)
69
                    ->setTarget($this->target_locale)
70
                    ->translate($this->word);
71
            } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type TopviewDigital\TranslationHelper\Service\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
72
                $this->break++;
73
                $mins = rand(
74
                    floor($this->called),
75
                    floor($this->called * rand(2, 5))
76
                ) * $this->break;
77
                sleep($mins * 60);
78
            }
79
        }
80
        return $translated;
81
    }
82
}
83