| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
/*
|
|
|
4 |
* This file is part of the Symfony package.
|
|
|
5 |
*
|
|
|
6 |
* (c) Fabien Potencier <fabien@symfony.com>
|
|
|
7 |
*
|
|
|
8 |
* For the full copyright and license information, please view the LICENSE
|
|
|
9 |
* file that was distributed with this source code.
|
|
|
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 |
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
|
|
|
19 |
* @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
|
|
|
20 |
*/
|
|
|
21 |
class IntlFormatter implements IntlFormatterInterface
|
|
|
22 |
{
|
|
|
23 |
private $hasMessageFormatter;
|
|
|
24 |
private $cache = [];
|
|
|
25 |
|
|
|
26 |
public function formatIntl(string $message, string $locale, array $parameters = []): string
|
|
|
27 |
{
|
|
|
28 |
// MessageFormatter constructor throws an exception if the message is empty
|
|
|
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 |
}
|