Add replacements to the L class
sebsel opened this issue · comments
For translation purposes it would be nice if you can use %s
(or similar) to replace certain words in certain phrases.
Example from Dutch:
'likes %s' > 'vindt %s leuk'
In Dutch (and German and many other languages) word-order is not always what it is in English. Replacements are very useful then :)
Here's a bit of what could work:
class L extends Silo {
public static $data = array();
public static function get($key = null, $default = null, $replacements = array()) {
if(empty($key)) return static::$data;
if(empty($replacements)) {
return isset(static::$data[$key]) ? static::$data[$key] : $default;
} else {
if(isset(static::$data[$key])) {
array_unshift($replacements, static::$data[$key]);
} else {
array_unshift($replacements, $default);
}
return call('sprintf', $replacements);
}
}
}
I agree that we should introduce some kind of placeholders.
However I think we should use MessageFormatter here to make it even more flexible. What do you think?
I never heard of MessageFormatter, but sure! Does it do strings? I see only numbers as replacements.
MessageFormat is a pretty powerful language, it can do all sorts of language-specific formatting such as numbers, money, plurals etc.
Of course it also supports simple strings:
{name} likes {item}
I already have a first version ready, but what would you do when MessageFormatter is not available? Fall back to simple string replacements or throw an error?
As far as I can tell it's bundled with PHP.
But you are right, there might be situations where users have disabled the extension.
I think we shouldn't try to emulate it though. It's waay to powerful and there is no way we would get that right. Maybe we should require it when using replacements. If replacements are not used, it doesn't matter anyway and this is an optional feature.
At least the default PHP installation on macOS comes without the extension. I think you are right though. We throw an error if you try to use it for replacements. Otherwise it will be ignored. It's pretty brilliant btw. Haven't heard about it before.
Just pushed my version to the develop branch. Works great!