| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Translation\Formatter; |
| 13 |
|
| 14 |
use Symfony\Component\Translation\Exception\InvalidArgumentException; |
| 15 |
use Symfony\Component\Translation\Exception\LogicException; |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
class IntlFormatter implements IntlFormatterInterface |
| 22 |
{ |
| 23 |
private bool $hasMessageFormatter; |
| 24 |
private array $cache = []; |
| 25 |
|
| 26 |
public function formatIntl(string $message, string $locale, array $parameters = []): string |
| 27 |
{ |
| 28 |
|
| 29 |
if ('' === $message) { |
| 30 |
return ''; |
| 31 |
} |
| 32 |
|
| 33 |
if (!$formatter = $this->cache[$locale][$message] ?? null) { |
| 34 |
if (!$this->hasMessageFormatter ??= class_exists(\MessageFormatter::class)) { |
| 35 |
throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.'); |
| 36 |
} |
| 37 |
try { |
| 38 |
$this->cache[$locale][$message] = $formatter = new \MessageFormatter($locale, $message); |
| 39 |
} catch (\IntlException $e) { |
| 40 |
throw new InvalidArgumentException(\sprintf('Invalid message format (error #%d): ', intl_get_error_code()).intl_get_error_message(), 0, $e); |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
foreach ($parameters as $key => $value) { |
| 45 |
if (\in_array($key[0] ?? null, ['%', '{'], true)) { |
| 46 |
unset($parameters[$key]); |
| 47 |
$parameters[trim($key, '%{ }')] = $value; |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
if (false === $message = $formatter->format($parameters)) { |
| 52 |
throw new InvalidArgumentException(\sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()).$formatter->getErrorMessage()); |
| 53 |
} |
| 54 |
|
| 55 |
return $message; |
| 56 |
} |
| 57 |
} |