IntlFormatter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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): %s.', 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): %s.', $formatter->getErrorCode(), $formatter->getErrorMessage()));
  48. }
  49. return $message;
  50. }
  51. }