we are now using custom translations for our project in PHP and I want to migrate them to Symfony ones. Everything looks great, but my only concern is that variable placeholders needs key to bind successfully, can I somehow change the code to accept translation variables in sequence (without keys)?
Let me show an example:
Our code now:
$translator->translate('For the period %date%, %data%', [$dateInterval, $additionalData]);
But this is how Symfony wants it:
return $this->symfonyTranslator->trans('For the period %date%, %data%', ['%date%' => $dateInterval, '%data%' => $additionalData]);
This is what I want:
return $this->symfonyTranslator->trans('For the period %date%, %data%', [$dateInterval, $additionalData]);
Is this somehow possible? I didn’t find it anywhere in the documentation and Google didn’t help either.
Advertisement
Answer
I have solved it by myself this is the code (in case anyone needs it):
Basically, it gets all %variables% and sets them as array keys with corresponding array values from $parameters variable.
public function translate(string $gettextString, array $parameters = []): string { $gettextString = $this->newlinesNormalizer->normalize($gettextString); preg_match_all('~%(S+)%~m', $gettextString, $matches); $variables = $matches[array_key_last($matches)]; $finalParameters = []; foreach ($variables as $index => $variable) { if (substr($variable, 0, 1) === '%' && substr($variable, -1) === '%') { continue; } $finalParameters['%' . $variable . '%'] = $parameters[$index]; } return $this->symfonyTranslator->trans($gettextString, $finalParameters); }