Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit e99dd52

Browse files
update translate method return
1 parent 1f2993a commit e99dd52

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

src/DeepL.php

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ public function __destruct()
121121
* @param $sourceLanguage string
122122
* @param $destinationLanguage string
123123
*
124-
* @return array
124+
* @return string|string[]
125125
*
126126
* @throws DeepLException
127127
*/
@@ -130,9 +130,22 @@ public function translate($text, $sourceLanguage = 'de', $destinationLanguage =
130130
// make sure we only accept supported languages
131131
$this->checkLanguages($sourceLanguage, $destinationLanguage);
132132

133+
// build the DeepL API request url
133134
$url = $this->buildUrl($text, $sourceLanguage, $destinationLanguage);
134135

135-
return $this->request($url);
136+
// request the DeepL API
137+
$translationsArray = $this->request($url);
138+
$translationsCount = count($translationsArray['translations']);
139+
140+
if ($translationsCount == 0) {
141+
throw new DeepLException('No translations found.');
142+
}
143+
else if ($translationsCount == 1) {
144+
return $translationsArray['translations'][0]['text'];
145+
}
146+
else {
147+
return $translationsArray['translations'];
148+
}
136149
}
137150

138151
/**
@@ -216,6 +229,10 @@ protected function request($url)
216229

217230
$translationsArray = json_decode($response, true);
218231

232+
if (!$translationsArray) {
233+
throw new DeepLException('The Response seems to not be valid JSON.');
234+
}
235+
219236
return $translationsArray;
220237
}
221238
}

tests/DeepLTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,9 @@ public function testTranslate()
102102

103103
$deepl = new DeepL($authKey);
104104

105-
$response = $deepl->translate($germanText);
105+
$translatedText = $deepl->translate($germanText);
106106

107-
$this->assertEquals('Hello World', $response['translations'][0]['text']);
107+
$this->assertEquals('Hello World', $translatedText);
108108
}
109109

110110
/**
@@ -121,6 +121,6 @@ public function testTranslateException()
121121

122122
$this->setExpectedException('\BabyMarkt\DeepL\DeepLException');
123123

124-
$response = $deepl->translate($germanText);
124+
$translatedText = $deepl->translate($germanText);
125125
}
126126
}

0 commit comments

Comments
 (0)