Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Google Translate uppercasing x0, x1... replacement placeholders #15

Merged
merged 2 commits into from
Jul 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions src/Drivers/Translation.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,28 +87,26 @@ public function getGoogleTranslate($language, $token)

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

// Step 3: Translate the modified text using Google Translate
$tr = new GoogleTranslate($language, $this->sourceLanguage);
$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);
}
//Note: we're using case-insensitive replace because Google Translate sometimes uppercases the x
$translatedText = str_ireplace($tempStrings, $placeholders, $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",
// Print a warning to stderr
fwrite(STDERR, sprintf(
"Warning: Placeholder count mismatch in translated text.\nOriginal text: %s\nTranslated text: %s\nExpected placeholders: %s\nActual placeholders: %s\n",
$token,
$translatedText,
json_encode($placeholders),
Expand Down
Loading