/
DeeplTranslator.php
53 lines (42 loc) · 1.31 KB
/
DeeplTranslator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace Ben182\AutoTranslate\Translators;
use Scn\DeeplApiConnector\DeeplClient;
use Scn\DeeplApiConnector\Model\TranslationConfig;
use Scn\DeeplApiConnector\Exception\RequestException;
use Ben182\AutoTranslate\Exceptions\LanguageCodeNotExist;
class DeeplTranslator implements TranslatorInterface
{
protected $translator;
protected $source;
protected $target;
public function __construct()
{
$this->translator = DeeplClient::create(config('auto-translate.deepl.api_key'));
}
public function setSource(string $source)
{
$this->source = strtoupper($source);
return $this;
}
public function setTarget(string $target)
{
$this->target = strtoupper($target);
return $this;
}
public function translate(string $string) : string
{
$translation = new TranslationConfig(
$string,
$this->target,
$this->source
);
try {
return $this->translator->getTranslation($translation)->getText();
} catch (RequestException $th) {
if ($th->getMessage() === '400 {"message":"Value for \'target_lang\' is not supported."}') {
throw LanguageCodeNotExist::throw($this->source, $this->target);
}
throw $th;
}
}
}