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

Commit f3f6ecc

Browse files
committed
Added Glossary endpoints. Updated tests and endpoints
1 parent 443772c commit f3f6ecc

File tree

3 files changed

+308
-18
lines changed

3 files changed

+308
-18
lines changed

README.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,58 @@ echo 'You have used '.$usageArray['character_count'].' of '.$usageArray['charact
113113

114114
```
115115

116+
### Glossary
117+
Create a glossary
118+
```php
119+
$glossary = $deepl->createGlossary('MyGlossary', ['Hallo' => 'Hello'], 'de', 'en');
120+
```
121+
122+
| param | Description |
123+
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
124+
| $name | Glossary name
125+
| $entries | Array of entries
126+
| $sourceLanguage | The source language into which the glossary rule apply |
127+
| $targetLanguage | The target language into which the glossary rule apply |
128+
129+
Delete a glossary
130+
```php
131+
$glossary = $deepl->deleteGlossary($glossaryId);
132+
```
133+
134+
| param | Description |
135+
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
136+
| $glossaryId | Glossary uuid (set by DeepL when glossary is created)
137+
138+
List glossaries
139+
```php
140+
$glossaries = $deepl->listGlossaries();
141+
foreach ($glossaries as $glossary) {
142+
var_dump($glossary);
143+
}
144+
```
145+
146+
Get glossary meta information: creation date, is glossary ready to use ...
147+
```php
148+
$glossaryInformation = $deepl->glossaryInformation($glossaryId);
149+
var_dump($glossaryInformation);
150+
```
151+
152+
| param | Description |
153+
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
154+
| $glossaryId | Glossary uuid (set by DeepL when glossary is created)
155+
156+
Get glossary entries
157+
```php
158+
$entries = $deepl->glossaryEntries($glossaryId);
159+
foreach ($entries as $sourceLangText => $targetLangText) {
160+
echo $sourceLangText .' > '.$targetLangText;
161+
}
162+
```
163+
164+
| param | Description |
165+
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
166+
| $glossaryId | Glossary uuid (set by DeepL when glossary is created)
167+
116168
### Configuring cURL requests
117169
If you need to use a proxy, you can configure the underlying curl client to use one. You can also specify a timeout to avoid waiting for several minutes if Deepl is unreachable
118170
```php

src/DeepL.php

Lines changed: 171 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,19 @@
1212
class DeepL
1313
{
1414
const API_URL_SCHEMA = 'https';
15+
1516
/**
1617
* API BASE URL
1718
* https://api.deepl.com/v2/[resource]?auth_key=[yourAuthKey]
1819
*/
1920
const API_URL_BASE = '%s://%s/v%s/%s?auth_key=%s';
2021

22+
/**
23+
* API BASE URL without authentication query parameter
24+
* https://api.deepl.com/v2/[resource]
25+
*/
26+
const API_URL_BASE_NO_AUTH = '%s://%s/v%s/%s';
27+
2128
/**
2229
* API URL: usage
2330
*/
@@ -28,6 +35,11 @@ class DeepL
2835
*/
2936
const API_URL_RESOURCE_LANGUAGES = 'languages';
3037

38+
/**
39+
* API URL: glossaries
40+
*/
41+
const API_URL_RESOURCE_GLOSSARIES = 'glossaries';
42+
3143
/**
3244
* DeepL API Version (v2 is default since 2018)
3345
*
@@ -227,6 +239,111 @@ public function usage()
227239
return $usage;
228240
}
229241

242+
/**
243+
* Calls the glossary-Endpoint and return Json-response as an array
244+
*
245+
* @return array
246+
* @throws DeepLException
247+
*/
248+
public function listGlossaries()
249+
{
250+
return $this->request($this->buildBaseUrl(self::API_URL_RESOURCE_GLOSSARIES), '', 'GET');
251+
}
252+
253+
/**
254+
* Creates a glossary, entries must be formatted as [sourceText => entryText] e.g: ['Hallo' => 'Hello']
255+
*
256+
* @param string $name
257+
* @param array $entries
258+
* @param string $sourceLang
259+
* @param string $targetLang
260+
* @param string $entriesFormat
261+
* @return array|null
262+
* @throws DeepLException
263+
*/
264+
public function createGlossary(
265+
string $name,
266+
array $entries,
267+
string $sourceLang = 'de',
268+
string $targetLang = 'en',
269+
string $entriesFormat = 'tsv'
270+
) {
271+
$formattedEntries = "";
272+
foreach ($entries as $source => $target) {
273+
$formattedEntries .= sprintf("%s\t%s\n", $source, $target);
274+
}
275+
276+
$paramsArray = [
277+
'name' => $name,
278+
'source_lang' => $sourceLang,
279+
'target_lang' => $targetLang,
280+
'entries' => $formattedEntries,
281+
'entries_format' => $entriesFormat
282+
];
283+
284+
$url = $this->buildBaseUrl(self::API_URL_RESOURCE_GLOSSARIES, false);
285+
$body = $this->buildQuery($paramsArray);
286+
287+
return $this->request($url, $body);
288+
}
289+
290+
/**
291+
* Deletes a glossary
292+
*
293+
* @param string $glossaryId
294+
* @return array|null
295+
* @throws DeepLException
296+
*/
297+
public function deleteGlossary(string $glossaryId)
298+
{
299+
$url = $this->buildBaseUrl(self::API_URL_RESOURCE_GLOSSARIES, false);
300+
$url .= "/$glossaryId";
301+
302+
return $this->request($url, '', 'DELETE');
303+
}
304+
305+
/**
306+
* Gets information about a glossary
307+
*
308+
* @param string $glossaryId
309+
* @return array|null
310+
* @throws DeepLException
311+
*/
312+
public function glossaryInformation(string $glossaryId)
313+
{
314+
$url = $this->buildBaseUrl(self::API_URL_RESOURCE_GLOSSARIES, false);
315+
$url .= "/$glossaryId";
316+
317+
return $this->request($url, '', 'GET');
318+
}
319+
320+
/**
321+
* Fetch glossary entries and format them as associative array [source => target]
322+
*
323+
* @param string $glossaryId
324+
* @return array
325+
* @throws DeepLException
326+
*/
327+
public function glossaryEntries(string $glossaryId)
328+
{
329+
$url = $this->buildBaseUrl(self::API_URL_RESOURCE_GLOSSARIES, false);
330+
$url .= "/$glossaryId/entries";
331+
332+
$response = $this->request($url, '', 'GET');
333+
334+
$entries = [];
335+
if (!empty($response)) {
336+
$allEntries = preg_split('/\n/', $response);
337+
foreach ($allEntries as $entry) {
338+
$sourceAndTarget = preg_split('/\s+/', rtrim($entry));
339+
if (isset($sourceAndTarget[0], $sourceAndTarget[1])) {
340+
$entries[$sourceAndTarget[0]] = $sourceAndTarget[1];
341+
}
342+
}
343+
}
344+
345+
return $entries;
346+
}
230347

231348
/**
232349
* Creates the Base-Url which all of the 3 API-resources have in common.
@@ -235,18 +352,26 @@ public function usage()
235352
*
236353
* @return string
237354
*/
238-
protected function buildBaseUrl($resource = 'translate')
355+
protected function buildBaseUrl($resource = 'translate', $withAuth = true)
239356
{
240-
$url = sprintf(
241-
self::API_URL_BASE,
357+
if ($withAuth) {
358+
return sprintf(
359+
self::API_URL_BASE,
360+
self::API_URL_SCHEMA,
361+
$this->host,
362+
$this->apiVersion,
363+
$resource,
364+
$this->authKey
365+
);
366+
}
367+
368+
return sprintf(
369+
self::API_URL_BASE_NO_AUTH,
242370
self::API_URL_SCHEMA,
243371
$this->host,
244372
$this->apiVersion,
245-
$resource,
246-
$this->authKey
373+
$resource
247374
);
248-
249-
return $url;
250375
}
251376

252377
/**
@@ -280,25 +405,38 @@ protected function buildQuery($paramsArray)
280405
return $body;
281406
}
282407

283-
284-
285-
286408
/**
287409
* Make a request to the given URL
288410
*
289411
* @param string $url
290412
* @param string $body
413+
* @param string $method
291414
*
292415
* @return array
293416
*
294417
* @throws DeepLException
295418
*/
296-
protected function request($url, $body = '')
419+
protected function request($url, $body = '', $method = 'POST')
297420
{
298-
curl_setopt($this->curl, CURLOPT_POST, true);
421+
switch ($method) {
422+
case 'DELETE':
423+
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
424+
break;
425+
case 'POST':
426+
curl_setopt($this->curl, CURLOPT_POST, true);
427+
break;
428+
default:
429+
break;
430+
}
431+
299432
curl_setopt($this->curl, CURLOPT_URL, $url);
300-
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
433+
434+
if ($method === 'POST') {
435+
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
436+
}
437+
301438
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
439+
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array("Authorization: DeepL-Auth-Key $this->authKey"));
302440

303441
if ($this->proxy !== null) {
304442
curl_setopt($this->curl, CURLOPT_PROXY, $this->proxy);
@@ -317,14 +455,31 @@ protected function request($url, $body = '')
317455
if (curl_errno($this->curl)) {
318456
throw new DeepLException('There was a cURL Request Error : ' . curl_error($this->curl));
319457
}
320-
$httpCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
458+
$httpCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
459+
460+
return $this->handleResponse($response, $httpCode);
461+
}
462+
463+
/**
464+
* Handles the different kind of response returned from API, array, string or null
465+
*
466+
* @param $response
467+
* @param $httpCode
468+
* @return array|mixed|null
469+
* @throws DeepLException
470+
*/
471+
private function handleResponse($response, $httpCode)
472+
{
321473
$responseArray = json_decode($response, true);
474+
if (($httpCode === 200 || $httpCode === 204) && is_null($responseArray)) {
475+
return empty($response) ? null : $response;
476+
}
322477

323-
if ($httpCode != 200 && is_array($responseArray) && array_key_exists('message', $responseArray)) {
478+
if ($httpCode !== 200 && is_array($responseArray) && array_key_exists('message', $responseArray)) {
324479
throw new DeepLException($responseArray['message'], $httpCode);
325480
}
326481

327-
if (false === is_array($responseArray)) {
482+
if (!is_array($responseArray)) {
328483
throw new DeepLException('The Response seems to not be valid JSON.', $httpCode);
329484
}
330485

@@ -338,7 +493,6 @@ protected function request($url, $body = '')
338493
*/
339494
private function removeEmptyParams($paramsArray)
340495
{
341-
342496
foreach ($paramsArray as $key => $value) {
343497
if (true === empty($value)) {
344498
unset($paramsArray[$key]);

0 commit comments

Comments
 (0)