yiisoft / translator

Message translation
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
23 stars 9 forks source link

Feature: Translator return null for missing translations #115

Open tomaszkane opened 1 year ago

tomaszkane commented 1 year ago

What steps will reproduce the problem?

Use Translator on not-existed key.

echo $translator->translate('not.existed.key'); // "not.existed.key"

What is the expected result?

I want to decide when translate() should return key or null.

$translationsForFooCategory = [
  'label.some.existed.key' => 'Hello!',
];

$someOutput =  $translator->translate('label.some.existed.key', category: 'foo');
$someOutput .= $translator->translate('description.some.not.existed.key', category: 'foo');

echo $someOutput; // "Hello!"

Throwing exception on missing translations is to complicated here.

I want to decide if given translate category return null on missing key or given TranlateInterface instance.

Additional info

Q A
Version 3.0.0
PHP version 8.0
xepozz commented 1 year ago

What would you do with that null?

tomaszkane commented 1 year ago

Nothing. It just "This key does not have translation, so return nothing". I create translations for RBAC items:

return [
    'label.foo-read' => 'Foo label - it should be requred',
    'description.foo-read' => 'Foo description - its optional.',
    'label.boo-delete' => 'Boo',
//    'description.boo-delete' => 'Boo description is not necessary.',
];

Now I must set EventDispatcherInterface and catch exceptions or write dummy IF's like:


$translated = $translator->translate('description.boo-delete', category: 'foo');
if ('description.boo-delete' !== $translated) {
  $someOutput .= $translated;
}
xepozz commented 1 year ago

I think we may add some fallback function to let users decide what to do with missing translations. But null is impossible because of return type.

Will it be ok for you?

tomaszkane commented 1 year ago

Empty string is ok.