Skip to content

Commit

Permalink
Merge pull request #8 from aw-studio/feat/add-opt-api-params-and-chec…
Browse files Browse the repository at this point in the history
…k-json

Add api params to config, checks for json strings
  • Loading branch information
jannescb authored Jan 20, 2022
2 parents 6e2f0d7 + 7b5057f commit d728791
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
12 changes: 12 additions & 0 deletions config/deeplable.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,16 @@
'translated_models' => [
// App\Models\Post::class,
],

/*
|--------------------------------------------------------------------------
| API-Parameters
|--------------------------------------------------------------------------
|
| Here you can set optional api parameters.
|
*/
'api_params' => [
//'tag_handling' => 'xml', // only available in pro version
],
];
31 changes: 25 additions & 6 deletions src/Deepl.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class Deepl
* Create new Deepl instance.
*
* @param string $apiToken
* @param string $apiUrl
* @param string $fallbackLocale
* @return void
*/
public function __construct(
Expand All @@ -44,13 +46,23 @@ public function translate(string $string, string $targetLang, string|null $sourc
if (! $string) {
return '';
}
if ($this->isJson($string)) {
return $string;
}

if (str_contains($this->apiUrl, '-free')) {
$string = strip_tags($string);
}

$body = [
'auth_key' => $this->apiToken,
'text' => strip_tags($string, '<h1>,<h2>,<h3>,<h4>,<h5>,<h6>,<p>,<br>,<div>,<span>,<strong>,<b>,<a>'),
'source_language' => strtoupper($sourceLanguage ?: $this->fallbackLocale),
'target_lang' => strtoupper($targetLang),
];
$body = array_merge(
[
'auth_key' => $this->apiToken,
'text' => $string,
'source_language' => strtoupper($sourceLanguage ?: $this->fallbackLocale),
'target_lang' => strtoupper($targetLang),
],
config('deeplable.api_params')
);

$content = $this->apiCall('POST', 'translate', [
'query' => $body,
Expand Down Expand Up @@ -79,4 +91,11 @@ protected function apiCall($method, $action, $params = []): array

return json_decode($response->getBody(), true);
}

public function isJson($string)
{
json_decode($string);

return json_last_error() === JSON_ERROR_NONE;
}
}

0 comments on commit d728791

Please sign in to comment.