Formatter.php 16.3 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\base;

use Yii;
use DateTime;
use yii\helpers\HtmlPurifier;
use yii\helpers\Html;

/**
 * Formatter provides a set of commonly used data formatting methods.
 *
 * The formatting methods provided by Formatter are all named in the form of `asXyz()`.
 * The behavior of some of them may be configured via the properties of Formatter. For example,
 * by configuring [[dateFormat]], one may control how [[asDate()]] formats the value into a date string.
 *
22
 * Formatter is configured as an application component in [[\yii\base\Application]] by default.
23 24
 * You can access that instance via `Yii::$app->formatter`.
 *
Qiang Xue committed
25 26 27 28 29
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Formatter extends Component
{
30
	/**
31
	 * @var string the timezone to use for formatting time and date values.
32 33 34
	 * This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
	 * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
	 * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
35
	 * If this property is not set, [[\yii\base\Application::timezone]] will be used.
36 37
	 */
	public $timeZone;
Qiang Xue committed
38 39 40 41 42 43 44 45 46 47 48 49
	/**
	 * @var string the default format string to be used to format a date using PHP date() function.
	 */
	public $dateFormat = 'Y/m/d';
	/**
	 * @var string the default format string to be used to format a time using PHP date() function.
	 */
	public $timeFormat = 'h:i:s A';
	/**
	 * @var string the default format string to be used to format a date and time using PHP date() function.
	 */
	public $datetimeFormat = 'Y/m/d h:i:s A';
50
	/**
51
	 * @var string the text to be displayed when formatting a null. Defaults to '<span class="not-set">(not set)</span>'.
52 53
	 */
	public $nullDisplay;
Qiang Xue committed
54 55
	/**
	 * @var array the text to be displayed when formatting a boolean value. The first element corresponds
Alexander Makarov committed
56
	 * to the text display for false, the second element for true. Defaults to `['No', 'Yes']`.
Qiang Xue committed
57 58
	 */
	public $booleanFormat;
59 60
	/**
	 * @var string the character displayed as the decimal point when formatting a number.
61
	 * If not set, "." will be used.
62
	 */
63
	public $decimalSeparator;
64 65
	/**
	 * @var string the character displayed as the thousands separator character when formatting a number.
66
	 * If not set, "," will be used.
67
	 */
68
	public $thousandSeparator;
69 70 71 72 73
	/**
	 * @var array the format used to format size (bytes). Three elements may be specified: "base", "decimals" and "decimalSeparator".
	 * They correspond to the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte, defaults to 1024),
	 * the number of digits after the decimal point (defaults to 2) and the character displayed as the decimal point.
	 */
74 75 76 77 78
	public $sizeFormat = [
		'base' => 1024,
		'decimals' => 2,
		'decimalSeparator' => null,
	];
Qiang Xue committed
79 80 81 82 83 84

	/**
	 * Initializes the component.
	 */
	public function init()
	{
85 86 87 88
		if ($this->timeZone === null) {
			$this->timeZone = Yii::$app->timeZone;
		}

Qiang Xue committed
89
		if (empty($this->booleanFormat)) {
Alexander Makarov committed
90
			$this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')];
Qiang Xue committed
91
		}
92
		if ($this->nullDisplay === null) {
93
			$this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)') . '</span>';
94
		}
Qiang Xue committed
95 96
	}

Qiang Xue committed
97
	/**
98
	 * Formats the value based on the given format type.
Qiang Xue committed
99
	 * This method will call one of the "as" methods available in this class to do the formatting.
100 101
	 * For type "xyz", the method "asXyz" will be used. For example, if the format is "html",
	 * then [[asHtml()]] will be used. Format names are case insensitive.
Qiang Xue committed
102
	 * @param mixed $value the value to be formatted
103 104 105
	 * @param string|array $format the format of the value, e.g., "html", "text". To specify additional
	 * parameters of the formatting method, you may use an array. The first element of the array
	 * specifies the format name, while the rest of the elements will be used as the parameters to the formatting
Alexander Makarov committed
106
	 * method. For example, a format of `['date', 'Y-m-d']` will cause the invocation of `asDate($value, 'Y-m-d')`.
Qiang Xue committed
107 108 109
	 * @return string the formatting result
	 * @throws InvalidParamException if the type is not supported by this class.
	 */
110
	public function format($value, $format)
Qiang Xue committed
111
	{
112 113 114 115 116 117 118 119 120
		if (is_array($format)) {
			if (!isset($format[0])) {
				throw new InvalidParamException('The $format array must contain at least one element.');
			}
			$f = $format[0];
			$format[0] = $value;
			$params = $format;
			$format = $f;
		} else {
Alexander Makarov committed
121
			$params = [$value];
122 123
		}
		$method = 'as' . $format;
124
		if ($this->hasMethod($method)) {
Alexander Makarov committed
125
			return call_user_func_array([$this, $method], $params);
Qiang Xue committed
126
		} else {
127
			throw new InvalidParamException("Unknown type: $format");
Qiang Xue committed
128 129 130
		}
	}

Qiang Xue committed
131 132 133 134 135 136 137 138
	/**
	 * Formats the value as is without any formatting.
	 * This method simply returns back the parameter without any format.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asRaw($value)
	{
139 140 141
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
142 143 144 145 146 147 148 149 150 151
		return $value;
	}

	/**
	 * Formats the value as an HTML-encoded plain text.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asText($value)
	{
152 153 154
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
155 156 157 158 159 160 161 162 163 164
		return Html::encode($value);
	}

	/**
	 * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asNtext($value)
	{
165 166 167
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
168 169 170 171 172 173 174 175 176 177 178 179
		return nl2br(Html::encode($value));
	}

	/**
	 * Formats the value as HTML-encoded text paragraphs.
	 * Each text paragraph is enclosed within a `<p>` tag.
	 * One or multiple consecutive empty lines divide two paragraphs.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asParagraphs($value)
	{
180 181 182
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		return str_replace('<p></p>', '',
			'<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>'
		);
	}

	/**
	 * Formats the value as HTML text.
	 * The value will be purified using [[HtmlPurifier]] to avoid XSS attacks.
	 * Use [[asRaw()]] if you do not want any purification of the value.
	 * @param mixed $value the value to be formatted
	 * @param array|null $config the configuration for the HTMLPurifier class.
	 * @return string the formatted result
	 */
	public function asHtml($value, $config = null)
	{
198 199 200
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
201 202 203 204 205 206 207 208 209 210
		return HtmlPurifier::process($value, $config);
	}

	/**
	 * Formats the value as a mailto link.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asEmail($value)
	{
211 212 213
		if ($value === null) {
			return $this->nullDisplay;
		}
214
		return Html::mailto(Html::encode($value), $value);
Qiang Xue committed
215 216 217 218 219 220 221 222 223
	}

	/**
	 * Formats the value as an image tag.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asImage($value)
	{
224 225 226
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
227 228 229 230 231 232 233 234 235 236
		return Html::img($value);
	}

	/**
	 * Formats the value as a hyperlink.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 */
	public function asUrl($value)
	{
237 238 239
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
		$url = $value;
		if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
			$url = 'http://' . $url;
		}
		return Html::a(Html::encode($value), $url);
	}

	/**
	 * Formats the value as a boolean.
	 * @param mixed $value the value to be formatted
	 * @return string the formatted result
	 * @see booleanFormat
	 */
	public function asBoolean($value)
	{
255 256 257
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
258 259 260 261 262 263 264 265
		return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
	}

	/**
	 * Formats the value as a date.
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
266
	 * - an integer representing a UNIX timestamp
Qiang Xue committed
267 268 269 270
	 * - 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.
271
	 * If null, [[dateFormat]] will be used. The format string should be one
Qiang Xue committed
272 273 274 275 276 277
	 * that can be recognized by the PHP `date()` function.
	 * @return string the formatted result
	 * @see dateFormat
	 */
	public function asDate($value, $format = null)
	{
278 279 280
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
281
		$value = $this->normalizeDatetimeValue($value);
282
		return $this->formatTimestamp($value, $format === null ? $this->dateFormat : $format);
Qiang Xue committed
283 284 285 286 287 288 289
	}

	/**
	 * Formats the value as a time.
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
290
	 * - an integer representing a UNIX timestamp
Qiang Xue committed
291 292 293 294
	 * - 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.
295
	 * If null, [[timeFormat]] will be used. The format string should be one
Qiang Xue committed
296 297 298 299 300 301
	 * that can be recognized by the PHP `date()` function.
	 * @return string the formatted result
	 * @see timeFormat
	 */
	public function asTime($value, $format = null)
	{
302 303 304
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
305
		$value = $this->normalizeDatetimeValue($value);
306
		return $this->formatTimestamp($value, $format === null ? $this->timeFormat : $format);
Qiang Xue committed
307 308 309 310 311 312 313
	}

	/**
	 * Formats the value as a datetime.
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
314
	 * - an integer representing a UNIX timestamp
Qiang Xue committed
315 316 317 318
	 * - 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.
319
	 * If null, [[datetimeFormat]] will be used. The format string should be one
Qiang Xue committed
320 321 322 323 324 325
	 * that can be recognized by the PHP `date()` function.
	 * @return string the formatted result
	 * @see datetimeFormat
	 */
	public function asDatetime($value, $format = null)
	{
326 327 328
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
329
		$value = $this->normalizeDatetimeValue($value);
330
		return $this->formatTimestamp($value, $format === null ? $this->datetimeFormat : $format);
Qiang Xue committed
331 332 333 334 335
	}

	/**
	 * Normalizes the given datetime value as one that can be taken by various date/time formatting methods.
	 * @param mixed $value the datetime value to be normalized.
336
	 * @return integer the normalized datetime value
Qiang Xue committed
337 338 339 340
	 */
	protected function normalizeDatetimeValue($value)
	{
		if (is_string($value)) {
Qiang Xue committed
341
			return is_numeric($value) || $value === '' ? (int)$value : strtotime($value);
Qiang Xue committed
342 343 344 345 346 347 348
		} elseif ($value instanceof DateTime) {
			return $value->getTimestamp();
		} else {
			return (int)$value;
		}
	}

349 350 351 352 353
	/**
	 * @param integer $value normalized datetime value
	 * @param string $format the format used to convert the value into a date string.
	 * @return string the formatted result
	 */
Vladimir Zbrailov committed
354
	protected function formatTimestamp($value, $format)
355
	{
356
		$date = new DateTime(null, new \DateTimeZone($this->timeZone));
357
		$date->setTimestamp($value);
Vladimir Zbrailov committed
358
		return $date->format($format);
359 360
	}

Qiang Xue committed
361 362 363 364 365 366 367
	/**
	 * Formats the value as an integer.
	 * @param mixed $value the value to be formatted
	 * @return string the formatting result.
	 */
	public function asInteger($value)
	{
368 369 370
		if ($value === null) {
			return $this->nullDisplay;
		}
Qiang Xue committed
371 372 373 374 375 376 377 378 379 380
		if (is_string($value) && preg_match('/^(-?\d+)/', $value, $matches)) {
			return $matches[1];
		} else {
			$value = (int)$value;
			return "$value";
		}
	}

	/**
	 * Formats the value as a double number.
381
	 * Property [[decimalSeparator]] will be used to represent the decimal point.
Qiang Xue committed
382 383 384
	 * @param mixed $value the value to be formatted
	 * @param integer $decimals the number of digits after the decimal point
	 * @return string the formatting result.
385
	 * @see decimalSeparator
Qiang Xue committed
386 387 388
	 */
	public function asDouble($value, $decimals = 2)
	{
389 390 391
		if ($value === null) {
			return $this->nullDisplay;
		}
392 393 394 395 396
		if ($this->decimalSeparator === null) {
			return sprintf("%.{$decimals}f", $value);
		} else {
			return str_replace('.', $this->decimalSeparator, sprintf("%.{$decimals}f", $value));
		}
Qiang Xue committed
397 398 399
	}

	/**
Qiang Xue committed
400 401
	 * Formats the value as a number with decimal and thousand separators.
	 * This method calls the PHP number_format() function to do the formatting.
Qiang Xue committed
402 403 404
	 * @param mixed $value the value to be formatted
	 * @param integer $decimals the number of digits after the decimal point
	 * @return string the formatted result
405 406
	 * @see decimalSeparator
	 * @see thousandSeparator
Qiang Xue committed
407
	 */
408
	public function asNumber($value, $decimals = 0)
Qiang Xue committed
409
	{
410 411 412
		if ($value === null) {
			return $this->nullDisplay;
		}
413 414 415
		$ds = isset($this->decimalSeparator) ? $this->decimalSeparator: '.';
		$ts = isset($this->thousandSeparator) ? $this->thousandSeparator: ',';
		return number_format($value, $decimals, $ds, $ts);
Qiang Xue committed
416
	}
417 418

	/**
419 420 421 422
	 * Formats the value in bytes as a size in human readable form.
	 * @param integer $value value in bytes to be formatted
	 * @param boolean $verbose if full names should be used (e.g. bytes, kilobytes, ...).
	 * Defaults to false meaning that short names will be used (e.g. B, KB, ...).
423
	 * @return string the formatted result
424
	 * @see sizeFormat
425
	 */
Vincent committed
426
	public function asSize($value, $verbose = false)
427
	{
Vincent committed
428
		$position = 0;
429

Vincent committed
430 431 432 433
		do {
			if ($value < $this->sizeFormat['base']) {
				break;
			}
434

Vincent committed
435 436
			$value = $value / $this->sizeFormat['base'];
			$position++;
437
		} while ($position < 6);
438

Vincent committed
439
		$value = round($value, $this->sizeFormat['decimals']);
440 441 442
		$formattedValue = isset($this->sizeFormat['decimalSeparator']) ? str_replace('.', $this->sizeFormat['decimalSeparator'], $value) : $value;
		$params = ['n' => $formattedValue];
		
443
		switch($position) {
444
			case 0:
445
				return $verbose ? Yii::t('yii', '{n, plural, =1{# byte} other{# bytes}}', $params) : Yii::t('yii', '{n} B', $params);
446
			case 1:
447
				return $verbose ? Yii::t('yii', '{n, plural, =1{# kilobyte} other{# kilobytes}}', $params) : Yii::t('yii', '{n} KB', $params);
448
			case 2:
449
				return $verbose ? Yii::t('yii', '{n, plural, =1{# megabyte} other{# megabytes}}', $params) : Yii::t('yii', '{n} MB', $params);
450
			case 3:
451
				return $verbose ? Yii::t('yii', '{n, plural, =1{# gigabyte} other{# gigabytes}}', $params) : Yii::t('yii', '{n} GB', $params);
452
			case 4:
453
				return $verbose ? Yii::t('yii', '{n, plural, =1{# terabyte} other{# terabytes}}', $params) : Yii::t('yii', '{n} TB', $params);
454
			default:
455
				return $verbose ? Yii::t('yii', '{n, plural, =1{# petabyte} other{# petabytes}}', $params) : Yii::t('yii', '{n} PB', $params);
456
		}
457
	}
458 459

	/**
David Renty committed
460
	 * Formats the value as the time elapsed since then in human readable form.
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
	 * @param integer|string|DateTime $value the value to be formatted. The following
	 * types of value are supported:
	 *
	 * - an integer representing a UNIX timestamp
	 * - a string that can be parsed into a UNIX timestamp via `strtotime()`
	 * - a PHP DateTime object
	 *
	 * @return string the formatted result
	 */
	public function asElapsedTime($value)
	{
		if ($value === null) {
			return $this->nullDisplay;
		}
		$value = $this->normalizeDatetimeValue($value);

		$now = new \DateTime();
		$date = new DateTime(null, new \DateTimeZone($this->timeZone));
		$date->setTimestamp($value);

		$interval = $now->diff($date);

		if ($interval->y >= 1) {
			$delta = $interval->y;
485
			return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $delta]);
486 487
		} elseif ($interval->m >= 1) {
			$delta = $interval->m;
488
			return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $delta]);
489 490
		} elseif ($interval->d >= 7) {
			$delta = floor($interval->d / 7);
491
			return Yii::t('yii', '{delta, plural, =1{a week} other{# weeks}} ago', ['delta' => $delta]);
492 493
		} elseif ($interval->d >= 1) {
			$delta = $interval->d;
494
			return Yii::t('yii', '{delta, plural, =1{yesterday} other{# days ago}}', ['delta' => $delta]);
495 496
		} elseif ($interval->h >= 1) {
			$delta = $interval->h;
497
			return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $delta]);
498 499
		} elseif ($interval->i >= 1) {
			$delta = $interval->i;
500
			return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $delta]);
501 502
		} else {
			$delta = $interval->s;
503
			return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $delta]);
504 505
		}
	}
Qiang Xue committed
506
}