Skip to content

Commit

Permalink
Prevent placeholders from being auto-translated
Browse files Browse the repository at this point in the history
- Replace placeholders with temporary unique strings (e.g., x0, x1,
  etc.) before sending to Google Translate
- Restore original placeholders after translation
  • Loading branch information
q-- committed Jul 1, 2024
1 parent 51eb4fc commit 43c4fa7
Showing 1 changed file with 41 additions and 3 deletions.
44 changes: 41 additions & 3 deletions src/Drivers/Translation.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,55 @@ public function autoTranslate($language = false)
* @return string|null
* @throws \ErrorException
*/
public function getGoogleTranslate($language,$token){
public function getGoogleTranslate($language, $token)
{
$placeholderRegex = '/:([a-zA-Z0-9_]+)/';

// Step 1: Identify placeholders
preg_match_all($placeholderRegex, $token, $matches);
$placeholders = $matches[0];

// Step 2: Replace placeholders with temporary unique strings
$modifiedToken = $token;
$placeholderMap = [];
foreach ($placeholders as $index => $placeholder) {
$tempString = 'x' . $index;
$placeholderMap[$tempString] = $placeholder;
$modifiedToken = str_replace($placeholder, $tempString, $modifiedToken);
}

// Step 3: Translate the modified text using Google Translate
$tr = new GoogleTranslate($language, $this->sourceLanguage);
return $tr->translate($token);
$translatedText = $tr->translate($modifiedToken);

// Step 4: Replace the temporary unique strings back with the original placeholders
foreach ($placeholderMap as $tempString => $placeholder) {
$translatedText = str_replace($tempString, $placeholder, $translatedText);
}

// Step 5: Check if the number of placeholders has stayed the same
preg_match_all($placeholderRegex, $translatedText, $translatedMatches);
if (count($translatedMatches[0]) !== count($placeholders)) {
// Display an error or warning with more details
throw new \ErrorException(sprintf(
"Placeholder count mismatch in translated text.\nOriginal text: %s\nTranslated text: %s\nExpected placeholders: %s\nActual placeholders: %s",
$token,
$translatedText,
json_encode($placeholders),
json_encode($translatedMatches[0])
));
}

return $translatedText;
}

/**
* Loop through all the keys and get translated text from Google Translate
*
* @param $language
*/
public function translateLanguage($language){
public function translateLanguage($language)
{
//No need to translate e.g. English to English
if ($language === $this->sourceLanguage) {
return;
Expand Down

0 comments on commit 43c4fa7

Please sign in to comment.