MessageFormatter.php 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\i18n;

10 11
use yii\base\Component;
use yii\base\NotSupportedException;
12

13
/**
14 15 16
 * 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.
Qiang Xue committed
17 18
 *
 * The following enhancements are provided:
19
 *
20
 * - It accepts named arguments and mixed numeric and named arguments.
21 22
 * - Issues no error when an insufficient number of arguments have been provided. Instead, the placeholders will not be
 *   substituted.
Qiang Xue committed
23
 * - Fixes PHP 5.5 weird placeholder replacement in case no arguments are provided at all (https://bugs.php.net/bug.php?id=65920).
24 25 26
 * - 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.
27
 *
28
 *   The fallback implementation only supports the following message formats:
29
 *   - plural formatting for english ('one' and 'other' selectors)
30 31 32
 *   - select format
 *   - simple parameters
 *   - integer number parameters
33
 *
34 35 36
 *   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.
37
 *
38 39
 * @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.
40
 *
41
 * @author Alexander Makarov <sam@rmcreative.ru>
42
 * @author Carsten Brandt <mail@cebe.cc>
43 44
 * @since 2.0
 */
45
class MessageFormatter extends Component
46
{
47 48 49
	private $_errorCode = 0;
	private $_errorMessage = '';

50
	/**
51
	 * Get the error code from the last operation
52
	 * @link http://php.net/manual/en/messageformatter.geterrorcode.php
53
	 * @return string Code of the last error.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	 */
	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;
	}

	/**
71 72 73 74 75
	 * 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.
76
	 *
77 78
	 * @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.
79 80
	 * @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
81
	 */
82
	public function format($pattern, $params, $language)
83
	{
84 85 86 87
		$this->_errorCode = 0;
		$this->_errorMessage = '';

		if ($params === []) {
88
			return $pattern;
89 90 91
		}

		if (!class_exists('MessageFormatter', false)) {
Carsten Brandt committed
92
			return $this->fallbackFormat($pattern, $params, $language);
93 94
		}

95
		if (version_compare(PHP_VERSION, '5.5.0', '<') || version_compare(INTL_ICU_VERSION, '4.8', '<')) {
96 97 98
			// replace named arguments
			$pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
			$params = $newParams;
99
		}
100

101
		$formatter = new \MessageFormatter($language, $pattern);
102
		if ($formatter === null) {
103 104
			$this->_errorCode = intl_get_error_code();
			$this->_errorMessage = "Message pattern is invalid: " . intl_get_error_message();
105 106 107 108 109 110 111 112 113
			return false;
		}
		$result = $formatter->format($params);
		if ($result === false) {
			$this->_errorCode = $formatter->getErrorCode();
			$this->_errorMessage = $formatter->getErrorMessage();
			return false;
		} else {
			return $result;
114
		}
115 116 117
	}

	/**
118
	 * Parses an input string according to an [ICU message format](http://userguide.icu-project.org/formatparse/messages) pattern.
119
	 *
120
	 * It uses the PHP intl extension's [MessageFormatter::parse()](http://www.php.net/manual/en/messageformatter.parsemessage.php)
Carsten Brandt committed
121
	 * and adds support for named arguments.
122 123 124 125
	 * 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.
126
	 * @param string $language The locale to use for formatting locale-dependent parts
127
	 * @return array|boolean An array containing items extracted, or `FALSE` on error.
128
	 * @throws \yii\base\NotSupportedException when PHP intl extension is not installed.
129
	 */
130
	public function parse($pattern, $message, $language)
131
	{
132 133 134 135 136
		$this->_errorCode = 0;
		$this->_errorMessage = '';

		if (!class_exists('MessageFormatter', false)) {
			throw new NotSupportedException('You have to install PHP intl extension to use this feature.');
137 138
		}

139 140
		// replace named arguments
		if (($tokens = $this->tokenizePattern($pattern)) === false) {
141 142
			$this->_errorCode = -1;
			$this->_errorMessage = "Message pattern is invalid.";
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
			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);

159 160
		$formatter = new \MessageFormatter($language, $pattern);
		if ($formatter === null) {
161 162
			$this->_errorCode = -1;
			$this->_errorMessage = "Message pattern is invalid.";
163
			return false;
164
		}
165 166 167 168 169 170
		$result = $formatter->parse($message);
		if ($result === false) {
			$this->_errorCode = $formatter->getErrorCode();
			$this->_errorMessage = $formatter->getErrorMessage();
			return false;
		} else {
171 172 173 174 175
			$values = [];
			foreach($result as $key => $value) {
				$values[$map[$key]] = $value;
			}
			return $values;
176
		}
177 178 179
	}

	/**
180
	 * Replace named placeholders with numeric placeholders and quote unused.
181
	 *
Alexander Makarov committed
182
	 * @param string $pattern The pattern string to replace things into.
183 184 185
	 * @param array $args The array of values to insert into the format string.
	 * @return string The pattern string with placeholders replaced.
	 */
186
	private function replaceNamedArguments($pattern, $givenParams, &$resultingParams, &$map = [])
187
	{
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
		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;
220
					}
221 222
					$subpattern = $this->replaceNamedArguments(implode(',', $subtokens[$k]), $givenParams, $resultingParams, $map);
					$subtokens[$k] = $quote . '{' . $quote . $subpattern . $quote . '}' . $quote;
223
				}
224
				$token[2] = implode('', $subtokens);
225
			}
226
			$tokens[$i] = $quote . '{' . $quote . implode(',', $token) . $quote . '}' . $quote;
227
		}
228
		return implode('', $tokens);
229
	}
230 231 232

	/**
	 * Fallback implementation for MessageFormatter::formatMessage
233 234 235
	 * @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
236 237
	 * @return string|boolean The formatted pattern string or `FALSE` if an error occurred
	 */
238
	protected function fallbackFormat($pattern, $args, $locale)
239 240
	{
		if (($tokens = $this->tokenizePattern($pattern)) === false) {
241 242
			$this->_errorCode = -1;
			$this->_errorMessage = "Message pattern is invalid.";
243 244 245 246 247
			return false;
		}
		foreach($tokens as $i => $token) {
			if (is_array($token)) {
				if (($tokens[$i] = $this->parseToken($token, $args, $locale)) === false) {
248 249
					$this->_errorCode = -1;
					$this->_errorMessage = "Message pattern is invalid.";
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
					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)];
269
		while (true) {
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
			$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)
	{
308 309 310
		// parsing pattern based on ICU grammar:
		// http://icu-project.org/apiref/icu4c/classMessageFormat.html#details

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
		$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.");
328 329 330 331 332
			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.");
333 334 335 336 337
			case 'none': return $arg;
			case 'select':
				/* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html
				selectStyle = (selector '{' message '}')+
				*/
338 339 340
				if (!isset($token[2])) {
					return false;
				}
341 342 343
				$select = static::tokenizePattern($token[2]);
				$c = count($select);
				$message = false;
344
				for ($i = 0; $i + 1 < $c; $i++) {
345 346 347 348 349 350 351 352 353
					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) {
354
					return $this->fallbackFormat($message, $args, $locale);
355 356 357 358 359 360 361 362 363 364 365
				}
			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
				*/
366 367 368
				if (!isset($token[2])) {
					return false;
				}
369 370 371 372
				$plural = static::tokenizePattern($token[2]);
				$c = count($plural);
				$message = false;
				$offset = 0;
373
				for ($i = 0; $i + 1 < $c; $i++) {
374 375 376 377 378 379 380 381 382 383
					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 ||
384
						$selector == 'one' && $arg - $offset == 1
385 386 387 388 389
					) {
						$message = implode(',', str_replace('#', $arg - $offset, $plural[$i]));
					}
				}
				if ($message !== false) {
390
					return $this->fallbackFormat($message, $args, $locale);
391 392 393 394 395
				}
				break;
		}
		return false;
	}
396
}