Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
JorisvanW committed Mar 15, 2019
1 parent 3be4a2f commit 98d3311
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"JorisvanW\\DeepL\\Laravel\\DeepLServiceProvider"
],
"aliases": {
"DeepL": "JorisvanW\\DeepL\\Laravel\\Facade"
"DeepL": "JorisvanW\\DeepL\\Laravel\\Facades\\DeepL"
}
}
}
Expand Down
47 changes: 42 additions & 5 deletions src/Wrappers/DeepLApiWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function translations()
}

/**
* Translate a text with DeepL.
* Translate a collection of translations with \JorisvanW\DeepL\Api\Resources\Translate items from DeepL.
*
* @param string $text
* @param string $to
Expand All @@ -98,9 +98,46 @@ public function translate(
$from = TranslateType::LANG_AUTO,
$options = []
) {
return $this->client->translations->translate($text,
$to = TranslateType::LANG_EN,
$from = TranslateType::LANG_AUTO,
$options = []);
$regexTemp = [];

// Prevent translating the :keys (and make it cheaper)
if (!array_get($options, 'translate_keys', false) && preg_match_all('~(:\w+)~', $text, $matches, PREG_PATTERN_ORDER)) {
foreach ($matches[1] as $key => $word) {
$regexTemp["_{$key}"] = $word;
}

$text = str_replace(array_values($regexTemp), array_keys($regexTemp), $text);
}

$response = $this->client->translations->translate($text, $to, $from, $options = []);

if (!empty($regexTemp)) {
foreach ($response->translations as $key => $translation) {
/** @var text */
$response->translations[$key]->text = str_replace(array_keys($regexTemp), array_values($regexTemp), $translation->text);
}
}

return $response;
}

/**
* Translate a text with DeepL.
*
* @param string $text
* @param string $to
* @param string $from
* @param array $options
*
* @return string
* @throws \JorisvanW\DeepL\Api\Exceptions\ApiException
*/
public function translateText(
$text,
$to = TranslateType::LANG_EN,
$from = TranslateType::LANG_AUTO,
$options = []
) {
return $this->translate($text, $to, $from, $options)->translations[0]->text;
}
}

0 comments on commit 98d3311

Please sign in to comment.