IntlFormatter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 bool $hasMessageFormatter;
  20. private array $cache = [];
  21. public function formatIntl(string $message, string $locale, array $parameters = []): string
  22. {
  23. // MessageFormatter constructor throws an exception if the message is empty
  24. if ('' === $message) {
  25. return '';
  26. }
  27. if (!$formatter = $this->cache[$locale][$message] ?? null) {
  28. if (!$this->hasMessageFormatter ??= class_exists(\MessageFormatter::class)) {
  29. throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.');
  30. }
  31. try {
  32. $this->cache[$locale][$message] = $formatter = new \MessageFormatter($locale, $message);
  33. } catch (\IntlException $e) {
  34. throw new InvalidArgumentException(sprintf('Invalid message format (error #%d): ', intl_get_error_code()).intl_get_error_message(), 0, $e);
  35. }
  36. }
  37. foreach ($parameters as $key => $value) {
  38. if (\in_array($key[0] ?? null, ['%', '{'], true)) {
  39. unset($parameters[$key]);
  40. $parameters[trim($key, '%{ }')] = $value;
  41. }
  42. }
  43. if (false === $message = $formatter->format($parameters)) {
  44. throw new InvalidArgumentException(sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()).$formatter->getErrorMessage());
  45. }
  46. return $message;
  47. }
  48. }