blob: f7f1c36a2a1274e2464271a1eeef2f61a5505714 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?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
12namespace Symfony\Component\Translation\Formatter;
13
14use Symfony\Component\Translation\Exception\InvalidArgumentException;
15use Symfony\Component\Translation\Exception\LogicException;
16
17/**
18 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
19 * @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
20 */
21class IntlFormatter implements IntlFormatterInterface
22{
23 private $hasMessageFormatter;
24 private $cache = [];
25
26 /**
27 * {@inheritdoc}
28 */
29 public function formatIntl(string $message, string $locale, array $parameters = []): string
30 {
31 // MessageFormatter constructor throws an exception if the message is empty
32 if ('' === $message) {
33 return '';
34 }
35
36 if (!$formatter = $this->cache[$locale][$message] ?? null) {
37 if (!($this->hasMessageFormatter ?? $this->hasMessageFormatter = class_exists(\MessageFormatter::class))) {
38 throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.');
39 }
40 try {
41 $this->cache[$locale][$message] = $formatter = new \MessageFormatter($locale, $message);
42 } catch (\IntlException $e) {
43 throw new InvalidArgumentException(sprintf('Invalid message format (error #%d): ', intl_get_error_code()).intl_get_error_message(), 0, $e);
44 }
45 }
46
47 foreach ($parameters as $key => $value) {
48 if (\in_array($key[0] ?? null, ['%', '{'], true)) {
49 unset($parameters[$key]);
50 $parameters[trim($key, '%{ }')] = $value;
51 }
52 }
53
54 if (false === $message = $formatter->format($parameters)) {
55 throw new InvalidArgumentException(sprintf('Unable to format message (error #%s): ', $formatter->getErrorCode()).$formatter->getErrorMessage());
56 }
57
58 return $message;
59 }
60}