Language: Add function to replace string specifiers with i18n placeholder

pull/4978/head
Angel Fernando Quiroz Campos 1 year ago
parent e645d16e81
commit 792f101939
  1. 28
      src/CoreBundle/Command/UpdateVueTranslations.php

@ -70,7 +70,7 @@ class UpdateVueTranslations extends Command
$newLanguage = []; $newLanguage = [];
foreach ($translations as $variable => $translation) { foreach ($translations as $variable => $translation) {
$translated = $this->translator->trans($variable, [], null, $iso); $translated = $this->translator->trans($variable, [], null, $iso);
$newLanguage[$variable] = $translated; $newLanguage[$variable] = $this->replaceMarkers($translated);
} }
$newLanguageToString = json_encode($newLanguage, JSON_PRETTY_PRINT); $newLanguageToString = json_encode($newLanguage, JSON_PRETTY_PRINT);
$fileToSave = $vueLocalePath.$iso.'.json'; $fileToSave = $vueLocalePath.$iso.'.json';
@ -82,4 +82,30 @@ class UpdateVueTranslations extends Command
return Command::SUCCESS; return Command::SUCCESS;
} }
/**
* Replace specifiers in a string to allow rendering them by i18n
*
* <code>
* $txt = "Bonjour %s. Je m’appelle %s";
* $replaced = replaceMarkers($txt); // Bonjour {0}. Je m’appelle {1}
* </code>
*/
private function replaceMarkers(string $text): string
{
$count = 0;
$replace = function ($matches) use (&$count) {
$type = $matches[1];
return match ($type) {
"s", "d", "f" => "{".$count++."}",
default => $matches[0],
};
};
$pattern = "/%([sdf])/";
return preg_replace_callback($pattern, $replace, $text);
}
} }

Loading…
Cancel
Save