0 follower

Class Yiisoft\Translator\SimpleMessageFormatter

InheritanceYiisoft\Translator\SimpleMessageFormatter
ImplementsYiisoft\Translator\MessageFormatterInterface

Public Methods

Hide inherited methods

Method Description Defined By
format() Yiisoft\Translator\SimpleMessageFormatter

Constants

Hide inherited constants

Constant Value Description Defined By
PLURAL_KEYS [ self::PLURAL_ONE, self::PLURAL_OTHER, ] Yiisoft\Translator\SimpleMessageFormatter
PLURAL_ONE 'one' Yiisoft\Translator\SimpleMessageFormatter
PLURAL_OTHER 'other' Yiisoft\Translator\SimpleMessageFormatter

Method Details

Hide inherited methods

format() public method

public string format ( string $message, array $parameters, string $locale 'en-US' )
$message string
$parameters array
$locale string

                public function format(string $message, array $parameters, string $locale = 'en-US'): string
{
    preg_match_all('/{((?>[^{}]+)|(?R))*}/', $message, $matches);
    $replacements = [];
    foreach ($matches[0] as $match) {
        $parts = explode(',', $match);
        $parameter = trim($parts[0], '{} ');
        if ($parameter === '') {
            throw new InvalidArgumentException('Parameter\'s name can not be empty.');
        }
        if (!array_key_exists($parameter, $parameters)) {
            throw new InvalidArgumentException("\"$parameter\" parameter's value is missing.");
        }
        $value = $parameters[$parameter] ?? '';
        if (!is_scalar($value)) {
            continue;
        }
        if (count($parts) === 1) {
            $replacements[$match] = $value;
            continue;
        }
        $format = ltrim($parts[1]);
        $format = rtrim($format, '}');
        switch ($format) {
            case 'plural':
                $options = $parts[2] ?? '';
                $replacements[$match] = self::pluralize($value, $options);
                break;
            default:
                $replacements[$match] = $value;
        }
    }
    return strtr($message, $replacements);
}