Нема описа

IntlFormatter.php 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Translation\Formatter;
  11. use Symfony\Component\Translation\Exception\InvalidArgumentException;
  12. use Symfony\Component\Translation\Exception\LogicException;
  13. /**
  14. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  15. * @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
  16. */
  17. class IntlFormatter implements IntlFormatterInterface
  18. {
  19. private $hasMessageFormatter;
  20. private $cache = [];
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function formatIntl(string $message, string $locale, array $parameters = []): string
  25. {
  26. // MessageFormatter constructor throws an exception if the message is empty
  27. if ('' === $message) {
  28. return '';
  29. }
  30. if (!$formatter = $this->cache[$locale][$message] ?? null) {
  31. if (!($this->hasMessageFormatter ?? $this->hasMessageFormatter = class_exists(\MessageFormatter::class))) {
  32. throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.');
  33. }
  34. try {
  35. $this->cache[$locale][$message] = $formatter = new \MessageFormatter($locale, $message);
  36. } catch (\IntlException $e) {
  37. throw new InvalidArgumentException(sprintf('Invalid message format (error #%d): ', intl_get_error_code()).intl_get_error_message(), 0, $e);
  38. }
  39. }
  40. foreach ($parameters as $key => $value) {
  41. if (\in_array($key[0] ?? null, ['%', '{'], true)) {
  42. unset($parameters[$key]);
  43. $parameters[trim($key, '%{ }')] = $value;
  44. }
  45. }
  46. if (false === $message = $formatter->format($parameters)) {
  47. throw new InvalidArgumentException(sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()).$formatter->getErrorMessage());
  48. }
  49. return $message;
  50. }
  51. }