You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
397 lines
13 KiB
397 lines
13 KiB
11 years ago
|
<?php
|
||
|
/**
|
||
|
* @link http://www.yiiframework.com/
|
||
|
* @copyright Copyright (c) 2008 Yii Software LLC
|
||
|
* @license http://www.yiiframework.com/license/
|
||
|
*/
|
||
|
|
||
|
namespace yii\i18n;
|
||
|
|
||
11 years ago
|
use yii\base\Component;
|
||
|
use yii\base\NotSupportedException;
|
||
11 years ago
|
|
||
11 years ago
|
/**
|
||
11 years ago
|
* MessageFormatter allows formatting messages via [ICU message format](http://userguide.icu-project.org/formatparse/messages)
|
||
|
*
|
||
|
* This class enhances the message formatter class provided by the PHP intl extension.
|
||
11 years ago
|
*
|
||
|
* The following enhancements are provided:
|
||
11 years ago
|
*
|
||
11 years ago
|
* - It accepts named arguments and mixed numeric and named arguments.
|
||
11 years ago
|
* - Issues no error when an insufficient number of arguments have been provided. Instead, the placeholders will not be
|
||
|
* substituted.
|
||
11 years ago
|
* - Fixes PHP 5.5 weird placeholder replacement in case no arguments are provided at all (https://bugs.php.net/bug.php?id=65920).
|
||
11 years ago
|
* - Offers limited support for message formatting in case PHP intl extension is not installed.
|
||
|
* However it is highly recommended that you install [PHP intl extension](http://php.net/manual/en/book.intl.php) if you want
|
||
|
* to use MessageFormatter features.
|
||
11 years ago
|
*
|
||
11 years ago
|
* The fallback implementation only supports the following message formats:
|
||
11 years ago
|
* - plural formatting for english ('one' and 'other' selectors)
|
||
11 years ago
|
* - select format
|
||
|
* - simple parameters
|
||
|
* - integer number parameters
|
||
11 years ago
|
*
|
||
11 years ago
|
* The fallback implementation does NOT support the ['apostrophe-friendly' syntax](http://www.php.net/manual/en/messageformatter.formatmessage.php).
|
||
|
* Also messages that are working with the fallback implementation are not necessarily compatible with the
|
||
|
* PHP intl MessageFormatter so do not rely on the fallback if you are able to install intl extension somehow.
|
||
11 years ago
|
*
|
||
11 years ago
|
* @property string $errorCode Code of the last error. This property is read-only.
|
||
|
* @property string $errorMessage Description of the last error. This property is read-only.
|
||
11 years ago
|
*
|
||
11 years ago
|
* @author Alexander Makarov <sam@rmcreative.ru>
|
||
11 years ago
|
* @author Carsten Brandt <mail@cebe.cc>
|
||
11 years ago
|
* @since 2.0
|
||
|
*/
|
||
11 years ago
|
class MessageFormatter extends Component
|
||
11 years ago
|
{
|
||
11 years ago
|
private $_errorCode = 0;
|
||
|
private $_errorMessage = '';
|
||
|
|
||
11 years ago
|
/**
|
||
11 years ago
|
* Get the error code from the last operation
|
||
11 years ago
|
* @link http://php.net/manual/en/messageformatter.geterrorcode.php
|
||
11 years ago
|
* @return string Code of the last error.
|
||
11 years ago
|
*/
|
||
|
public function getErrorCode()
|
||
|
{
|
||
|
return $this->_errorCode;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Get the error text from the last operation
|
||
|
* @link http://php.net/manual/en/messageformatter.geterrormessage.php
|
||
|
* @return string Description of the last error.
|
||
|
*/
|
||
|
public function getErrorMessage()
|
||
|
{
|
||
|
return $this->_errorMessage;
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Formats a message via [ICU message format](http://userguide.icu-project.org/formatparse/messages)
|
||
|
*
|
||
|
* It uses the PHP intl extension's [MessageFormatter](http://www.php.net/manual/en/class.messageformatter.php)
|
||
|
* and works around some issues.
|
||
|
* If PHP intl is not installed a fallback will be used that supports a subset of the ICU message format.
|
||
11 years ago
|
*
|
||
11 years ago
|
* @param string $pattern The pattern string to insert parameters into.
|
||
|
* @param array $params The array of name value pairs to insert into the format string.
|
||
11 years ago
|
* @param string $language The locale to use for formatting locale-dependent parts
|
||
|
* @return string|boolean The formatted pattern string or `FALSE` if an error occurred
|
||
11 years ago
|
*/
|
||
11 years ago
|
public function format($pattern, $params, $language)
|
||
11 years ago
|
{
|
||
11 years ago
|
$this->_errorCode = 0;
|
||
|
$this->_errorMessage = '';
|
||
|
|
||
|
if ($params === []) {
|
||
11 years ago
|
return $pattern;
|
||
11 years ago
|
}
|
||
|
|
||
|
if (!class_exists('MessageFormatter', false)) {
|
||
11 years ago
|
return $this->fallbackFormat($pattern, $params, $language);
|
||
11 years ago
|
}
|
||
|
|
||
11 years ago
|
if (version_compare(PHP_VERSION, '5.5.0', '<') || version_compare(INTL_ICU_VERSION, '4.8', '<')) {
|
||
11 years ago
|
// replace named arguments
|
||
|
$pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
|
||
|
$params = $newParams;
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
11 years ago
|
$formatter = new \MessageFormatter($language, $pattern);
|
||
11 years ago
|
if ($formatter === null) {
|
||
11 years ago
|
$this->_errorCode = intl_get_error_code();
|
||
|
$this->_errorMessage = "Message pattern is invalid: " . intl_get_error_message();
|
||
11 years ago
|
return false;
|
||
|
}
|
||
|
$result = $formatter->format($params);
|
||
|
if ($result === false) {
|
||
|
$this->_errorCode = $formatter->getErrorCode();
|
||
|
$this->_errorMessage = $formatter->getErrorMessage();
|
||
|
return false;
|
||
|
} else {
|
||
|
return $result;
|
||
11 years ago
|
}
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Parses an input string according to an [ICU message format](http://userguide.icu-project.org/formatparse/messages) pattern.
|
||
11 years ago
|
*
|
||
11 years ago
|
* It uses the PHP intl extension's [MessageFormatter::parse()](http://www.php.net/manual/en/messageformatter.parsemessage.php)
|
||
11 years ago
|
* and adds support for named arguments.
|
||
11 years ago
|
* Usage of this method requires PHP intl extension to be installed.
|
||
|
*
|
||
|
* @param string $pattern The pattern to use for parsing the message.
|
||
|
* @param string $message The message to parse, conforming to the pattern.
|
||
11 years ago
|
* @param string $language The locale to use for formatting locale-dependent parts
|
||
11 years ago
|
* @return array|boolean An array containing items extracted, or `FALSE` on error.
|
||
11 years ago
|
* @throws \yii\base\NotSupportedException when PHP intl extension is not installed.
|
||
11 years ago
|
*/
|
||
11 years ago
|
public function parse($pattern, $message, $language)
|
||
11 years ago
|
{
|
||
11 years ago
|
$this->_errorCode = 0;
|
||
|
$this->_errorMessage = '';
|
||
|
|
||
|
if (!class_exists('MessageFormatter', false)) {
|
||
|
throw new NotSupportedException('You have to install PHP intl extension to use this feature.');
|
||
11 years ago
|
}
|
||
|
|
||
11 years ago
|
// replace named arguments
|
||
|
if (($tokens = $this->tokenizePattern($pattern)) === false) {
|
||
11 years ago
|
$this->_errorCode = -1;
|
||
|
$this->_errorMessage = "Message pattern is invalid.";
|
||
11 years ago
|
return false;
|
||
|
}
|
||
|
$map = [];
|
||
|
foreach($tokens as $i => $token) {
|
||
|
if (is_array($token)) {
|
||
|
$param = trim($token[0]);
|
||
|
if (!isset($map[$param])) {
|
||
|
$map[$param] = count($map);
|
||
|
}
|
||
|
$token[0] = $map[$param];
|
||
|
$tokens[$i] = '{' . implode(',', $token) . '}';
|
||
|
}
|
||
|
}
|
||
|
$pattern = implode('', $tokens);
|
||
|
$map = array_flip($map);
|
||
|
|
||
11 years ago
|
$formatter = new \MessageFormatter($language, $pattern);
|
||
|
if ($formatter === null) {
|
||
11 years ago
|
$this->_errorCode = -1;
|
||
|
$this->_errorMessage = "Message pattern is invalid.";
|
||
11 years ago
|
return false;
|
||
11 years ago
|
}
|
||
11 years ago
|
$result = $formatter->parse($message);
|
||
|
if ($result === false) {
|
||
|
$this->_errorCode = $formatter->getErrorCode();
|
||
|
$this->_errorMessage = $formatter->getErrorMessage();
|
||
|
return false;
|
||
|
} else {
|
||
11 years ago
|
$values = [];
|
||
|
foreach($result as $key => $value) {
|
||
|
$values[$map[$key]] = $value;
|
||
|
}
|
||
|
return $values;
|
||
11 years ago
|
}
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Replace named placeholders with numeric placeholders and quote unused.
|
||
11 years ago
|
*
|
||
11 years ago
|
* @param string $pattern The pattern string to replace things into.
|
||
11 years ago
|
* @param array $args The array of values to insert into the format string.
|
||
|
* @return string The pattern string with placeholders replaced.
|
||
|
*/
|
||
11 years ago
|
private function replaceNamedArguments($pattern, $givenParams, &$resultingParams, &$map = [])
|
||
11 years ago
|
{
|
||
11 years ago
|
if (($tokens = $this->tokenizePattern($pattern)) === false) {
|
||
|
return false;
|
||
|
}
|
||
|
foreach($tokens as $i => $token) {
|
||
|
if (!is_array($token)) {
|
||
|
continue;
|
||
|
}
|
||
|
$param = trim($token[0]);
|
||
|
if (isset($givenParams[$param])) {
|
||
|
// if param is given, replace it with a number
|
||
|
if (!isset($map[$param])) {
|
||
|
$map[$param] = count($map);
|
||
|
// make sure only used params are passed to format method
|
||
|
$resultingParams[$map[$param]] = $givenParams[$param];
|
||
|
}
|
||
|
$token[0] = $map[$param];
|
||
|
$quote = "";
|
||
|
} else {
|
||
|
// quote unused token
|
||
|
$quote = "'";
|
||
|
}
|
||
|
$type = isset($token[1]) ? trim($token[1]) : 'none';
|
||
|
// replace plural and select format recursively
|
||
|
if ($type == 'plural' || $type == 'select') {
|
||
|
if (!isset($token[2])) {
|
||
|
return false;
|
||
|
}
|
||
|
$subtokens = $this->tokenizePattern($token[2]);
|
||
|
$c = count($subtokens);
|
||
|
for ($k = 0; $k + 1 < $c; $k++) {
|
||
|
if (is_array($subtokens[$k]) || !is_array($subtokens[++$k])) {
|
||
|
return false;
|
||
11 years ago
|
}
|
||
11 years ago
|
$subpattern = $this->replaceNamedArguments(implode(',', $subtokens[$k]), $givenParams, $resultingParams, $map);
|
||
|
$subtokens[$k] = $quote . '{' . $quote . $subpattern . $quote . '}' . $quote;
|
||
11 years ago
|
}
|
||
11 years ago
|
$token[2] = implode('', $subtokens);
|
||
11 years ago
|
}
|
||
11 years ago
|
$tokens[$i] = $quote . '{' . $quote . implode(',', $token) . $quote . '}' . $quote;
|
||
11 years ago
|
}
|
||
11 years ago
|
return implode('', $tokens);
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
|
/**
|
||
|
* Fallback implementation for MessageFormatter::formatMessage
|
||
11 years ago
|
* @param string $pattern The pattern string to insert things into.
|
||
|
* @param array $args The array of values to insert into the format string
|
||
|
* @param string $locale The locale to use for formatting locale-dependent parts
|
||
11 years ago
|
* @return string|boolean The formatted pattern string or `FALSE` if an error occurred
|
||
|
*/
|
||
11 years ago
|
protected function fallbackFormat($pattern, $args, $locale)
|
||
11 years ago
|
{
|
||
|
if (($tokens = $this->tokenizePattern($pattern)) === false) {
|
||
11 years ago
|
$this->_errorCode = -1;
|
||
|
$this->_errorMessage = "Message pattern is invalid.";
|
||
11 years ago
|
return false;
|
||
|
}
|
||
|
foreach($tokens as $i => $token) {
|
||
|
if (is_array($token)) {
|
||
|
if (($tokens[$i] = $this->parseToken($token, $args, $locale)) === false) {
|
||
11 years ago
|
$this->_errorCode = -1;
|
||
|
$this->_errorMessage = "Message pattern is invalid.";
|
||
11 years ago
|
return false;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return implode('', $tokens);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Tokenizes a pattern by separating normal text from replaceable patterns
|
||
|
* @param string $pattern patter to tokenize
|
||
|
* @return array|bool array of tokens or false on failure
|
||
|
*/
|
||
|
private function tokenizePattern($pattern)
|
||
|
{
|
||
|
$depth = 1;
|
||
|
if (($start = $pos = mb_strpos($pattern, '{')) === false) {
|
||
|
return [$pattern];
|
||
|
}
|
||
|
$tokens = [mb_substr($pattern, 0, $pos)];
|
||
11 years ago
|
while (true) {
|
||
11 years ago
|
$open = mb_strpos($pattern, '{', $pos + 1);
|
||
|
$close = mb_strpos($pattern, '}', $pos + 1);
|
||
|
if ($open === false && $close === false) {
|
||
|
break;
|
||
|
}
|
||
|
if ($open === false) {
|
||
|
$open = mb_strlen($pattern);
|
||
|
}
|
||
|
if ($close > $open) {
|
||
|
$depth++;
|
||
|
$pos = $open;
|
||
|
} else {
|
||
|
$depth--;
|
||
|
$pos = $close;
|
||
|
}
|
||
|
if ($depth == 0) {
|
||
|
$tokens[] = explode(',', mb_substr($pattern, $start + 1, $pos - $start - 1), 3);
|
||
|
$start = $pos + 1;
|
||
|
$tokens[] = mb_substr($pattern, $start, $open - $start);
|
||
|
$start = $open;
|
||
|
}
|
||
|
}
|
||
|
if ($depth != 0) {
|
||
|
return false;
|
||
|
}
|
||
|
return $tokens;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Parses a token
|
||
|
* @param array $token the token to parse
|
||
|
* @param array $args arguments to replace
|
||
|
* @param string $locale the locale
|
||
|
* @return bool|string parsed token or false on failure
|
||
|
* @throws \yii\base\NotSupportedException when unsupported formatting is used.
|
||
|
*/
|
||
|
private function parseToken($token, $args, $locale)
|
||
|
{
|
||
11 years ago
|
// parsing pattern based on ICU grammar:
|
||
|
// http://icu-project.org/apiref/icu4c/classMessageFormat.html#details
|
||
|
|
||
11 years ago
|
$param = trim($token[0]);
|
||
|
if (isset($args[$param])) {
|
||
|
$arg = $args[$param];
|
||
|
} else {
|
||
|
return '{' . implode(',', $token) . '}';
|
||
|
}
|
||
|
$type = isset($token[1]) ? trim($token[1]) : 'none';
|
||
|
switch($type)
|
||
|
{
|
||
|
case 'date':
|
||
|
case 'time':
|
||
|
case 'spellout':
|
||
|
case 'ordinal':
|
||
|
case 'duration':
|
||
|
case 'choice':
|
||
|
case 'selectordinal':
|
||
|
throw new NotSupportedException("Message format '$type' is not supported. You have to install PHP intl extension to use this feature.");
|
||
11 years ago
|
case 'number':
|
||
|
if (is_int($arg) && (!isset($token[2]) || trim($token[2]) == 'integer')) {
|
||
|
return $arg;
|
||
|
}
|
||
|
throw new NotSupportedException("Message format 'number' is only supported for integer values. You have to install PHP intl extension to use this feature.");
|
||
11 years ago
|
case 'none': return $arg;
|
||
|
case 'select':
|
||
|
/* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html
|
||
|
selectStyle = (selector '{' message '}')+
|
||
|
*/
|
||
11 years ago
|
if (!isset($token[2])) {
|
||
|
return false;
|
||
|
}
|
||
11 years ago
|
$select = static::tokenizePattern($token[2]);
|
||
|
$c = count($select);
|
||
|
$message = false;
|
||
11 years ago
|
for ($i = 0; $i + 1 < $c; $i++) {
|
||
11 years ago
|
if (is_array($select[$i]) || !is_array($select[$i + 1])) {
|
||
|
return false;
|
||
|
}
|
||
|
$selector = trim($select[$i++]);
|
||
|
if ($message === false && $selector == 'other' || $selector == $arg) {
|
||
|
$message = implode(',', $select[$i]);
|
||
|
}
|
||
|
}
|
||
|
if ($message !== false) {
|
||
11 years ago
|
return $this->fallbackFormat($message, $args, $locale);
|
||
11 years ago
|
}
|
||
|
break;
|
||
|
case 'plural':
|
||
|
/* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html
|
||
|
pluralStyle = [offsetValue] (selector '{' message '}')+
|
||
|
offsetValue = "offset:" number
|
||
|
selector = explicitValue | keyword
|
||
|
explicitValue = '=' number // adjacent, no white space in between
|
||
|
keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
|
||
|
message: see MessageFormat
|
||
|
*/
|
||
11 years ago
|
if (!isset($token[2])) {
|
||
|
return false;
|
||
|
}
|
||
11 years ago
|
$plural = static::tokenizePattern($token[2]);
|
||
|
$c = count($plural);
|
||
|
$message = false;
|
||
|
$offset = 0;
|
||
11 years ago
|
for ($i = 0; $i + 1 < $c; $i++) {
|
||
11 years ago
|
if (is_array($plural[$i]) || !is_array($plural[$i + 1])) {
|
||
|
return false;
|
||
|
}
|
||
|
$selector = trim($plural[$i++]);
|
||
|
if ($i == 1 && substr($selector, 0, 7) == 'offset:') {
|
||
|
$offset = (int) trim(mb_substr($selector, 7, ($pos = mb_strpos(str_replace(["\n", "\r", "\t"], ' ', $selector), ' ', 7)) - 7));
|
||
|
$selector = trim(mb_substr($selector, $pos + 1));
|
||
|
}
|
||
|
if ($message === false && $selector == 'other' ||
|
||
|
$selector[0] == '=' && (int) mb_substr($selector, 1) == $arg ||
|
||
11 years ago
|
$selector == 'one' && $arg - $offset == 1
|
||
11 years ago
|
) {
|
||
|
$message = implode(',', str_replace('#', $arg - $offset, $plural[$i]));
|
||
|
}
|
||
|
}
|
||
|
if ($message !== false) {
|
||
11 years ago
|
return $this->fallbackFormat($message, $args, $locale);
|
||
11 years ago
|
}
|
||
|
break;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
11 years ago
|
}
|