Formatter.php 11.6 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\i18n;

use Yii;
use IntlDateFormatter;
use NumberFormatter;
use DateTime;
use yii\base\InvalidConfigException;

/**
 * Formatter is the localized version of [[\yii\base\Formatter]].
 *
 * Formatter requires the PHP "intl" extension to be installed. Formatter supports localized
 * formatting of date, time and numbers, based on the current [[locale]].
 *
22 23 24 25 26 27 28 29 30
 * This Formatter can replace the `formatter` application component that is configured by default.
 * To do so, add the following to your application config under `components`:
 *
 * ```php
 * 'formatter' => [
 *     'class' => 'yii\i18n\Formatter',
 * ]
 * ```
 *
Qiang Xue committed
31 32 33 34 35 36 37 38 39 40 41
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Formatter extends \yii\base\Formatter
{
	/**
	 * @var string the locale ID that is used to localize the date and number formatting.
	 * If not set, [[\yii\base\Application::language]] will be used.
	 */
	public $locale;
	/**
Qiang Xue committed
42 43 44
	 * @var string the default format string to be used to format a date.
	 * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
	 * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
Qiang Xue committed
45 46 47
	 */
	public $dateFormat = 'short';
	/**
Qiang Xue committed
48 49 50
	 * @var string the default format string to be used to format a time.
	 * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
	 * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
Qiang Xue committed
51 52 53
	 */
	public $timeFormat = 'short';
	/**
Qiang Xue committed
54 55 56
	 * @var string the default format string to be used to format a date and time.
	 * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
	 * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
Qiang Xue committed
57 58 59 60
	 */
	public $datetimeFormat = 'short';
	/**
	 * @var array the options to be set for the NumberFormatter objects. Please refer to
Qiang Xue committed
61 62 63
	 * [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
	 * for the possible options. This property is used by [[createNumberFormatter]] when
	 * creating a new number formatter to format decimals, currencies, etc.
Qiang Xue committed
64
	 */
Alexander Makarov committed
65
	public $numberFormatOptions = [];
66 67 68 69 70 71 72 73 74 75
	/**
	 * @var string the character displayed as the decimal point when formatting a number.
	 * If not set, the decimal separator corresponding to [[locale]] will be used.
	 */
	public $decimalSeparator;
	/**
	 * @var string the character displayed as the thousands separator character when formatting a number.
	 * If not set, the thousand separator corresponding to [[locale]] will be used.
	 */
	public $thousandSeparator;
Qiang Xue committed
76 77 78 79 80 81 82 83 84 85 86


	/**
	 * Initializes the component.
	 * This method will check if the "intl" PHP extension is installed and set the
	 * default value of [[locale]].
	 * @throws InvalidConfigException if the "intl" PHP extension is not installed.
	 */
	public function init()
	{
		if (!extension_loaded('intl')) {
87
			throw new InvalidConfigException('The "intl" PHP extension is not installed. It is required to format data values in localized formats.');
Qiang Xue committed
88 89 90 91
		}
		if ($this->locale === null) {
			$this->locale = Yii::$app->language;
		}
92 93 94
		if ($this->decimalSeparator === null || $this->thousandSeparator === null) {
			$formatter = new NumberFormatter($this->locale, NumberFormatter::DECIMAL);
			if ($this->decimalSeparator === null) {
Qiang Xue committed
95
				$this->decimalSeparator = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
96 97
			}
			if ($this->thousandSeparator === null) {
Qiang Xue committed
98
				$this->thousandSeparator = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
99 100 101
			}
		}

Qiang Xue committed
102 103 104
		parent::init();
	}

Alexander Makarov committed
105
	private $_dateFormats = [
Qiang Xue committed
106 107 108 109
		'short' => IntlDateFormatter::SHORT,
		'medium' => IntlDateFormatter::MEDIUM,
		'long' => IntlDateFormatter::LONG,
		'full' => IntlDateFormatter::FULL,
Alexander Makarov committed
110
	];
Qiang Xue committed
111 112 113 114 115 116

	/**
	 * Formats the value as a date.
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
117
	 * - an integer representing a UNIX timestamp
Qiang Xue committed
118 119 120 121
	 * - a string that can be parsed into a UNIX timestamp via `strtotime()`
	 * - a PHP DateTime object
	 *
	 * @param string $format the format used to convert the value into a date string.
Qiang Xue committed
122 123 124 125 126
	 * If null, [[dateFormat]] will be used.
	 *
	 * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
	 * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
	 *
Qiang Xue committed
127
	 * @return string the formatted result
128
	 * @throws InvalidConfigException when formatting fails due to invalid parameters.
Qiang Xue committed
129 130 131 132
	 * @see dateFormat
	 */
	public function asDate($value, $format = null)
	{
133 134 135
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
136 137 138 139 140
		$value = $this->normalizeDatetimeValue($value);
		if ($format === null) {
			$format = $this->dateFormat;
		}
		if (isset($this->_dateFormats[$format])) {
141
			$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
Qiang Xue committed
142
		} else {
143
			$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
144 145 146 147 148 149
			if ($formatter !== null) {
				$formatter->setPattern($format);
			}
		}
		if ($formatter === null) {
			throw new InvalidConfigException(intl_get_error_message());
Qiang Xue committed
150 151 152 153 154 155 156 157 158
		}
		return $formatter->format($value);
	}

	/**
	 * Formats the value as a time.
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
159
	 * - an integer representing a UNIX timestamp
Qiang Xue committed
160 161 162 163
	 * - a string that can be parsed into a UNIX timestamp via `strtotime()`
	 * - a PHP DateTime object
	 *
	 * @param string $format the format used to convert the value into a date string.
Qiang Xue committed
164 165 166 167 168
	 * If null, [[dateFormat]] will be used.
	 *
	 * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
	 * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
	 *
Qiang Xue committed
169
	 * @return string the formatted result
170
	 * @throws InvalidConfigException when formatting fails due to invalid parameters.
Qiang Xue committed
171 172 173 174
	 * @see timeFormat
	 */
	public function asTime($value, $format = null)
	{
175 176 177
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
178 179 180 181 182
		$value = $this->normalizeDatetimeValue($value);
		if ($format === null) {
			$format = $this->timeFormat;
		}
		if (isset($this->_dateFormats[$format])) {
183
			$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
Qiang Xue committed
184
		} else {
185
			$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
186 187 188 189 190 191
			if ($formatter !== null) {
				$formatter->setPattern($format);
			}
		}
		if ($formatter === null) {
			throw new InvalidConfigException(intl_get_error_message());
Qiang Xue committed
192 193 194 195 196 197 198 199 200
		}
		return $formatter->format($value);
	}

	/**
	 * Formats the value as a datetime.
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
201
	 * - an integer representing a UNIX timestamp
Qiang Xue committed
202 203 204 205
	 * - a string that can be parsed into a UNIX timestamp via `strtotime()`
	 * - a PHP DateTime object
	 *
	 * @param string $format the format used to convert the value into a date string.
Qiang Xue committed
206 207 208 209 210
	 * If null, [[dateFormat]] will be used.
	 *
	 * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
	 * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
	 *
Qiang Xue committed
211
	 * @return string the formatted result
212
	 * @throws InvalidConfigException when formatting fails due to invalid parameters.
Qiang Xue committed
213 214 215 216
	 * @see datetimeFormat
	 */
	public function asDatetime($value, $format = null)
	{
217 218 219
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
220 221 222 223 224
		$value = $this->normalizeDatetimeValue($value);
		if ($format === null) {
			$format = $this->datetimeFormat;
		}
		if (isset($this->_dateFormats[$format])) {
225
			$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
Qiang Xue committed
226
		} else {
227
			$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
228 229 230 231 232 233
			if ($formatter !== null) {
				$formatter->setPattern($format);
			}
		}
		if ($formatter === null) {
			throw new InvalidConfigException(intl_get_error_message());
Qiang Xue committed
234 235 236 237 238 239 240 241 242 243 244 245 246
		}
		return $formatter->format($value);
	}

	/**
	 * Formats the value as a decimal number.
	 * @param mixed $value the value to be formatted
	 * @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
	 * for details on how to specify a format.
	 * @return string the formatted result.
	 */
	public function asDecimal($value, $format = null)
	{
247 248 249
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
250
		return $this->createNumberFormatter(NumberFormatter::DECIMAL, $format)->format($value);
Qiang Xue committed
251 252 253 254 255 256 257 258 259 260 261 262
	}

	/**
	 * Formats the value as a currency number.
	 * @param mixed $value the value to be formatted
	 * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
	 * @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
	 * for details on how to specify a format.
	 * @return string the formatted result.
	 */
	public function asCurrency($value, $currency = 'USD', $format = null)
	{
263 264 265
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
266
		return $this->createNumberFormatter(NumberFormatter::CURRENCY, $format)->formatCurrency($value, $currency);
Qiang Xue committed
267 268 269 270 271 272 273 274 275 276 277
	}

	/**
	 * Formats the value as a percent number.
	 * @param mixed $value the value to be formatted
	 * @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
	 * for details on how to specify a format.
	 * @return string the formatted result.
	 */
	public function asPercent($value, $format = null)
	{
278 279 280
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
281
		return $this->createNumberFormatter(NumberFormatter::PERCENT, $format)->format($value);
Qiang Xue committed
282 283 284 285 286 287 288 289 290 291 292
	}

	/**
	 * Formats the value as a scientific number.
	 * @param mixed $value the value to be formatted
	 * @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
	 * for details on how to specify a format.
	 * @return string the formatted result.
	 */
	public function asScientific($value, $format = null)
	{
293 294 295
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
296
		return $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $format)->format($value);
Qiang Xue committed
297 298 299 300 301
	}

	/**
	 * Creates a number formatter based on the given type and format.
	 * @param integer $type the type of the number formatter
Qiang Xue committed
302
	 * @param string $format the format to be used.  Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
Qiang Xue committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	 * @return NumberFormatter the created formatter instance
	 */
	protected function createNumberFormatter($type, $format)
	{
		$formatter = new NumberFormatter($this->locale, $type);
		if ($format !== null) {
			$formatter->setPattern($format);
		}
		if (!empty($this->numberFormatOptions)) {
			foreach ($this->numberFormatOptions as $name => $attribute) {
				$formatter->setAttribute($name, $attribute);
			}
		}
		return $formatter;
	}
}