<?php
namespace Aura\Intl;
use MessageFormatter;
use Aura\Intl\Exception;
class IntlFormatter implements FormatterInterface
{
public function __construct($icu_version = INTL_ICU_VERSION)
{
if (version_compare($icu_version, '4.8') < 0) {
throw new Exception\IcuVersionTooLow('ICU Version 4.8 or higher required.');
}
}
public function format($locale, $string, array $tokens_values)
{
$values = [];
foreach ($tokens_values as $token => $value) {
if (is_array($value)) {
$value = '"' . implode('", "', $value) . '"';
}
$values[$token] = $value;
}
try {
$formatter = new MessageFormatter($locale, $string);
if (! $formatter) {
$this->throwCannotInstantiateFormatter();
}
} catch (\Exception $e) {
$this->throwCannotInstantiateFormatter();
}
$result = $formatter->format($values);
if ($result === false) {
throw new Exception\CannotFormat(
$formatter->getErrorMessage(),
$formatter->getErrorCode()
);
}
return $result;
}
protected function throwCannotInstantiateFormatter()
{
throw new Exception\CannotInstantiateFormatter(
intl_get_error_message(),
intl_get_error_code()
);
}
}