diff --git a/src/Translator.php b/src/Translator.php index 31aa71a..969c1b8 100644 --- a/src/Translator.php +++ b/src/Translator.php @@ -6,6 +6,7 @@ use Contributte\Translation\Tracy\Panel; use Contributte\Translation\Wrappers\Message; use Contributte\Translation\Wrappers\NotTranslate; +use Generator; use Nette\Localization\ITranslator; use Nette\Utils\Strings; use Nette\Utils\Validators; @@ -45,6 +46,9 @@ class Translator extends SymfonyTranslator implements ITranslator private string $initLang; + /** @var callable(mixed[] $params): Generator|null */ + private $translateKeyGenerator = null; + /** * @param array $cacheVary */ @@ -154,6 +158,27 @@ public function addPrefix( return $this; } + public function getTranslateKeyGenerator(): callable + { + if ($this->translateKeyGenerator === null) { + $this->translateKeyGenerator = function (array $params): Generator { + foreach ($params as $k1 => $v1) { + yield '%' . $k1 . '%' => $v1; + } + }; + } + + return $this->translateKeyGenerator; + } + + public function setTranslateKeyGenerator( + callable $generator + ): self + { + $this->translateKeyGenerator = $generator; + return $this; + } + /** * @throws \Contributte\Translation\Exceptions\InvalidArgument */ @@ -316,13 +341,9 @@ public function translate( [$domain, $message] = Helpers::extractMessage($message); } - $tmp = []; - - foreach ($params as $k1 => $v1) { - $tmp['%' . $k1 . '%'] = $v1; - } + $generator = $this->getTranslateKeyGenerator(); - $params = $tmp; + $params = iterator_to_array($generator($params)); if (Validators::isNumeric($count)) { $params += ['%count%' => $count]; diff --git a/tests/Tests/CustomTranslateKeyTest.phpt b/tests/Tests/CustomTranslateKeyTest.phpt new file mode 100644 index 0000000..c6869c2 --- /dev/null +++ b/tests/Tests/CustomTranslateKeyTest.phpt @@ -0,0 +1,45 @@ + 'Hi :name!', + ]; + + $translator = new Translator(new LocaleResolver(Mockery::mock(Container::class)), new FallbackResolver(), 'en', $this->container->getParameters()['tempDir'], true); + $translator->addLoader('array', new ArrayLoader()); + $translator->addResource('array', $translations, 'en'); + + Assert::same('Hi :name!', $translator->translate('hi', ['name' => 'Ales'])); + Assert::same('Hi :name!', $translator->translate(new Message('hi', ['name' => 'Ales']))); + + $translator->setTranslateKeyGenerator(function (array $params): Generator { + foreach ($params as $k1 => $v1) { + yield ':' . $k1 => $v1; + } + }); + + Assert::same('Hi Ales!', $translator->translate('hi', ['name' => 'Ales'])); + Assert::same('Hi Ales!', $translator->translate(new Message('hi', ['name' => 'Ales']))); + } + +} + +(new CustomTranslateKeyTest($container))->run();