translator icon indicating copy to clipboard operation
translator copied to clipboard

Feature: Translator return null for missing translations

Open tomaszkane opened this issue 2 years ago • 4 comments

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

tomaszkane avatar Apr 07 '23 09:04 tomaszkane

What would you do with that null?

xepozz avatar Apr 07 '23 09:04 xepozz

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;
}

tomaszkane avatar Apr 07 '23 10:04 tomaszkane

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?

xepozz avatar Apr 07 '23 12:04 xepozz

Empty string is ok.

tomaszkane avatar Apr 07 '23 12:04 tomaszkane