IntlFormatter.php
2 years ago
IntlFormatterInterface.php
2 years ago
MessageFormatter.php
1 month ago
MessageFormatterInterface.php
1 month ago
IntlFormatter.php
55 lines
| 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 | namespace IAWPSCOPED\Symfony\Component\Translation\Formatter; |
| 12 | |
| 13 | use IAWPSCOPED\Symfony\Component\Translation\Exception\InvalidArgumentException; |
| 14 | use IAWPSCOPED\Symfony\Component\Translation\Exception\LogicException; |
| 15 | /** |
| 16 | * @author Guilherme Blanco <guilhermeblanco@hotmail.com> |
| 17 | * @author Abdellatif Ait boudad <a.aitboudad@gmail.com> |
| 18 | * @internal |
| 19 | */ |
| 20 | class IntlFormatter implements IntlFormatterInterface |
| 21 | { |
| 22 | private $hasMessageFormatter; |
| 23 | private $cache = []; |
| 24 | /** |
| 25 | * {@inheritdoc} |
| 26 | */ |
| 27 | public function formatIntl(string $message, string $locale, array $parameters = []) : string |
| 28 | { |
| 29 | // MessageFormatter constructor throws an exception if the message is empty |
| 30 | if ('' === $message) { |
| 31 | return ''; |
| 32 | } |
| 33 | if (!($formatter = $this->cache[$locale][$message] ?? null)) { |
| 34 | if (!($this->hasMessageFormatter ?? ($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 | foreach ($parameters as $key => $value) { |
| 44 | if (\in_array($key[0] ?? null, ['%', '{'], \true)) { |
| 45 | unset($parameters[$key]); |
| 46 | $parameters[\trim($key, '%{ }')] = $value; |
| 47 | } |
| 48 | } |
| 49 | if (\false === ($message = $formatter->format($parameters))) { |
| 50 | throw new InvalidArgumentException(\sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()) . $formatter->getErrorMessage()); |
| 51 | } |
| 52 | return $message; |
| 53 | } |
| 54 | } |
| 55 |