IntlFormatter.php
2 months ago
IntlFormatterInterface.php
2 months ago
MessageFormatter.php
2 months ago
MessageFormatterInterface.php
2 months ago
IntlFormatter.php
54 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 ProfilePressVendor\Symfony\Component\Translation\Formatter; |
| 12 | |
| 13 | use ProfilePressVendor\Symfony\Component\Translation\Exception\InvalidArgumentException; |
| 14 | use ProfilePressVendor\Symfony\Component\Translation\Exception\LogicException; |
| 15 | /** |
| 16 | * @author Guilherme Blanco <guilhermeblanco@hotmail.com> |
| 17 | * @author Abdellatif Ait boudad <a.aitboudad@gmail.com> |
| 18 | */ |
| 19 | class IntlFormatter implements IntlFormatterInterface |
| 20 | { |
| 21 | private $hasMessageFormatter; |
| 22 | private $cache = []; |
| 23 | /** |
| 24 | * {@inheritdoc} |
| 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 | if (!$formatter = $this->cache[$locale][$message] ?? null) { |
| 33 | if (!($this->hasMessageFormatter ?? $this->hasMessageFormatter = class_exists(\MessageFormatter::class))) { |
| 34 | throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.'); |
| 35 | } |
| 36 | try { |
| 37 | $this->cache[$locale][$message] = $formatter = new \MessageFormatter($locale, $message); |
| 38 | } catch (\IntlException $e) { |
| 39 | throw new InvalidArgumentException(sprintf('Invalid message format (error #%d): ', intl_get_error_code()) . intl_get_error_message(), 0, $e); |
| 40 | } |
| 41 | } |
| 42 | foreach ($parameters as $key => $value) { |
| 43 | if (\in_array($key[0] ?? null, ['%', '{'], \true)) { |
| 44 | unset($parameters[$key]); |
| 45 | $parameters[trim($key, '%{ }')] = $value; |
| 46 | } |
| 47 | } |
| 48 | if (\false === $message = $formatter->format($parameters)) { |
| 49 | throw new InvalidArgumentException(sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()) . $formatter->getErrorMessage()); |
| 50 | } |
| 51 | return $message; |
| 52 | } |
| 53 | } |
| 54 |