Formatter.php 22.1 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
{
David Renty committed
30 31 32 33 34
    /**
     * @var string the timezone to use for formatting time and date values.
     * 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.
Carsten Brandt committed
35
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
David Renty committed
36 37 38 39 40
     */
    public $timeZone;
    /**
     * @var string the default format string to be used to format a date using PHP date() function.
     */
41
    public $dateFormat = 'Y-m-d';
David Renty committed
42 43 44
    /**
     * @var string the default format string to be used to format a time using PHP date() function.
     */
45
    public $timeFormat = 'H:i:s';
David Renty committed
46 47 48
    /**
     * @var string the default format string to be used to format a date and time using PHP date() function.
     */
49
    public $datetimeFormat = 'Y-m-d H:i:s';
David Renty committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    /**
     * @var string the text to be displayed when formatting a null. Defaults to '<span class="not-set">(not set)</span>'.
     */
    public $nullDisplay;
    /**
     * @var array the text to be displayed when formatting a boolean value. The first element corresponds
     * to the text display for false, the second element for true. Defaults to `['No', 'Yes']`.
     */
    public $booleanFormat;
    /**
     * @var string the character displayed as the decimal point when formatting a number.
     * If not set, "." will be used.
     */
    public $decimalSeparator;
    /**
     * @var string the character displayed as the thousands separator character when formatting a number.
     * If not set, "," will be used.
     */
    public $thousandSeparator;
    /**
     * @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.
     */
    public $sizeFormat = [
        'base' => 1024,
        'decimals' => 2,
        'decimalSeparator' => null,
    ];

80

David Renty committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    /**
     * Initializes the component.
     */
    public function init()
    {
        if ($this->timeZone === null) {
            $this->timeZone = Yii::$app->timeZone;
        }

        if (empty($this->booleanFormat)) {
            $this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')];
        }
        if ($this->nullDisplay === null) {
            $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)') . '</span>';
        }
    }

    /**
     * Formats the value based on the given format type.
     * This method will call one of the "as" methods available in this class to do the formatting.
     * 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.
103 104 105 106 107 108
     * @param mixed $value the value to be formatted
     * @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
     * method. For example, a format of `['date', 'Y-m-d']` will cause the invocation of `asDate($value, 'Y-m-d')`.
     * @return string the formatting result
David Renty committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
     * @throws InvalidParamException if the type is not supported by this class.
     */
    public function format($value, $format)
    {
        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 {
            $params = [$value];
        }
        $method = 'as' . $format;
        if ($this->hasMethod($method)) {
            return call_user_func_array([$this, $method], $params);
        } else {
            throw new InvalidParamException("Unknown type: $format");
        }
    }

    /**
     * Formats the value as is without any formatting.
     * This method simply returns back the parameter without any format.
135
     * @param mixed $value the value to be formatted
David Renty committed
136 137 138 139 140 141 142
     * @return string the formatted result
     */
    public function asRaw($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
143

David Renty committed
144 145 146 147 148
        return $value;
    }

    /**
     * Formats the value as an HTML-encoded plain text.
149
     * @param mixed $value the value to be formatted
David Renty committed
150 151 152 153 154 155 156
     * @return string the formatted result
     */
    public function asText($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
157

David Renty committed
158 159 160 161 162
        return Html::encode($value);
    }

    /**
     * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
163
     * @param mixed $value the value to be formatted
David Renty committed
164 165 166 167 168 169 170
     * @return string the formatted result
     */
    public function asNtext($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
171

David Renty committed
172 173 174 175 176 177 178
        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.
179
     * @param mixed $value the value to be formatted
David Renty committed
180 181 182 183 184 185 186
     * @return string the formatted result
     */
    public function asParagraphs($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
187

188
        return str_replace('<p></p>', '', '<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
David Renty committed
189 190 191 192 193 194
    }

    /**
     * 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.
195 196 197
     * @param mixed $value the value to be formatted
     * @param array|null $config the configuration for the HTMLPurifier class.
     * @return string the formatted result
David Renty committed
198 199 200 201 202 203
     */
    public function asHtml($value, $config = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
204

David Renty committed
205 206 207 208 209
        return HtmlPurifier::process($value, $config);
    }

    /**
     * Formats the value as a mailto link.
210
     * @param mixed $value the value to be formatted
David Renty committed
211 212 213 214 215 216 217
     * @return string the formatted result
     */
    public function asEmail($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
218

David Renty committed
219 220 221 222 223
        return Html::mailto(Html::encode($value), $value);
    }

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

David Renty committed
233 234 235 236 237
        return Html::img($value);
    }

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

David Renty committed
251 252 253 254 255
        return Html::a(Html::encode($value), $url);
    }

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

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

David Renty committed
291 292 293 294 295 296
        return $this->formatTimestamp($value, $format === null ? $this->dateFormat : $format);
    }

    /**
     * Formats the value as a time.
     * @param integer|string|DateTime $value the value to be formatted. The following
297
     * types of value are supported:
David Renty committed
298 299 300 301 302
     *
     * - an integer representing a UNIX timestamp
     * - a string that can be parsed into a UNIX timestamp via `strtotime()`
     * - a PHP DateTime object
     *
303 304 305
     * @param string $format the format used to convert the value into a date string.
     * If null, [[timeFormat]] will be used. The format string should be one
     * that can be recognized by the PHP `date()` function.
David Renty committed
306 307 308 309 310 311 312 313 314
     * @return string the formatted result
     * @see timeFormat
     */
    public function asTime($value, $format = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $value = $this->normalizeDatetimeValue($value);
315

David Renty committed
316 317 318 319 320 321
        return $this->formatTimestamp($value, $format === null ? $this->timeFormat : $format);
    }

    /**
     * Formats the value as a datetime.
     * @param integer|string|DateTime $value the value to be formatted. The following
322
     * types of value are supported:
David Renty committed
323 324 325 326 327
     *
     * - an integer representing a UNIX timestamp
     * - a string that can be parsed into a UNIX timestamp via `strtotime()`
     * - a PHP DateTime object
     *
328 329 330
     * @param string $format the format used to convert the value into a date string.
     * If null, [[datetimeFormat]] will be used. The format string should be one
     * that can be recognized by the PHP `date()` function.
David Renty committed
331 332 333 334 335 336 337 338 339
     * @return string the formatted result
     * @see datetimeFormat
     */
    public function asDatetime($value, $format = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $value = $this->normalizeDatetimeValue($value);
340

David Renty committed
341 342 343 344 345
        return $this->formatTimestamp($value, $format === null ? $this->datetimeFormat : $format);
    }

    /**
     * Normalizes the given datetime value as one that can be taken by various date/time formatting methods.
Kartik Visweswaran committed
346
     *
347
     * @param mixed $value the datetime value to be normalized.
David Renty committed
348 349 350 351 352
     * @return integer the normalized datetime value
     */
    protected function normalizeDatetimeValue($value)
    {
        if (is_string($value)) {
Kartik Visweswaran committed
353 354 355
            if (is_numeric($value) || $value === '') {
                $value = (double)$value;
            } else {
Qiang Xue committed
356 357 358 359 360
                try {
                    $date = new DateTime($value);
                } catch (\Exception $e) {
                    return false;
                }
Philippe Gaultier committed
361
                $value = (double)$date->format('U');
Kartik Visweswaran committed
362 363
            }
            return $value;
364
        } elseif ($value instanceof DateTime || $value instanceof \DateTimeInterface) {
Philippe Gaultier committed
365
            return (double)$value->format('U');
David Renty committed
366
        } else {
Kartik Visweswaran committed
367
            return (double)$value;
David Renty committed
368 369 370 371
        }
    }

    /**
372 373 374
     * @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
David Renty committed
375 376 377 378 379
     */
    protected function formatTimestamp($value, $format)
    {
        $date = new DateTime(null, new \DateTimeZone($this->timeZone));
        $date->setTimestamp($value);
380

David Renty committed
381 382 383 384 385
        return $date->format($format);
    }

    /**
     * Formats the value as an integer.
386
     * @param mixed $value the value to be formatted
David Renty committed
387 388 389 390 391 392 393 394 395 396
     * @return string the formatting result.
     */
    public function asInteger($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        if (is_string($value) && preg_match('/^(-?\d+)/', $value, $matches)) {
            return $matches[1];
        } else {
397 398
            $value = (int) $value;

David Renty committed
399 400 401 402 403 404 405
            return "$value";
        }
    }

    /**
     * Formats the value as a double number.
     * Property [[decimalSeparator]] will be used to represent the decimal point.
406 407 408
     * @param mixed $value the value to be formatted
     * @param integer $decimals the number of digits after the decimal point
     * @return string the formatting result.
David Renty committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
     * @see decimalSeparator
     */
    public function asDouble($value, $decimals = 2)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        if ($this->decimalSeparator === null) {
            return sprintf("%.{$decimals}f", $value);
        } else {
            return str_replace('.', $this->decimalSeparator, sprintf("%.{$decimals}f", $value));
        }
    }

    /**
     * Formats the value as a number with decimal and thousand separators.
     * This method calls the PHP number_format() function to do the formatting.
426 427 428
     * @param mixed $value the value to be formatted
     * @param integer $decimals the number of digits after the decimal point
     * @return string the formatted result
David Renty committed
429 430 431 432 433 434 435 436
     * @see decimalSeparator
     * @see thousandSeparator
     */
    public function asNumber($value, $decimals = 0)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
marsuboss committed
437 438
        $ds = isset($this->decimalSeparator) ? $this->decimalSeparator : '.';
        $ts = isset($this->thousandSeparator) ? $this->thousandSeparator : ',';
439

440
        return number_format((float) $value, $decimals, $ds, $ts);
David Renty committed
441 442 443 444
    }

    /**
     * Formats the value in bytes as a size in human readable form.
445 446 447
     * @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, ...).
448 449 450
     * @param boolean $binaryPrefix if binary prefixes should be used for base 1024
     * Defaults to true meaning that binary prefixes are used (e.g. kibibyte/KiB, mebibyte/MiB, ...).
     * @link http://en.wikipedia.org/wiki/Binary_prefix
451
     * @return string the formatted result
David Renty committed
452 453
     * @see sizeFormat
     */
454
    public function asSize($value, $verbose = false, $binaryPrefix = true)
David Renty committed
455 456 457 458 459 460 461 462 463 464
    {
        $position = 0;

        do {
            if ($value < $this->sizeFormat['base']) {
                break;
            }

            $value = $value / $this->sizeFormat['base'];
            $position++;
465
        } while ($position < 5);
David Renty committed
466 467 468 469

        $value = round($value, $this->sizeFormat['decimals']);
        $formattedValue = isset($this->sizeFormat['decimalSeparator']) ? str_replace('.', $this->sizeFormat['decimalSeparator'], $value) : $value;
        $params = ['n' => $formattedValue];
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        if ($binaryPrefix && $this->sizeFormat['base'] === 1024) {
            switch ($position) {
                case 0:
                    return $verbose ? Yii::t('yii', '{n, plural, =1{# byte} other{# bytes}}', $params) : Yii::t('yii', '{n} B', $params);
                case 1:
                    return $verbose ? Yii::t('yii', '{n, plural, =1{# kibibyte} other{# kibibytes}}', $params) : Yii::t('yii', '{n} KiB', $params);
                case 2:
                    return $verbose ? Yii::t('yii', '{n, plural, =1{# mebibyte} other{# mebibytes}}', $params) : Yii::t('yii', '{n} MiB', $params);
                case 3:
                    return $verbose ? Yii::t('yii', '{n, plural, =1{# gibibyte} other{# gibibytes}}', $params) : Yii::t('yii', '{n} GiB', $params);
                case 4:
                    return $verbose ? Yii::t('yii', '{n, plural, =1{# tebibyte} other{# tebibytes}}', $params) : Yii::t('yii', '{n} TiB', $params);
                default:
                    return $verbose ? Yii::t('yii', '{n, plural, =1{# pebibyte} other{# pebibytes}}', $params) : Yii::t('yii', '{n} PiB', $params);
            }
        }

488
        switch ($position) {
David Renty committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502
            case 0:
                return $verbose ? Yii::t('yii', '{n, plural, =1{# byte} other{# bytes}}', $params) : Yii::t('yii', '{n} B', $params);
            case 1:
                return $verbose ? Yii::t('yii', '{n, plural, =1{# kilobyte} other{# kilobytes}}', $params) : Yii::t('yii', '{n} KB', $params);
            case 2:
                return $verbose ? Yii::t('yii', '{n, plural, =1{# megabyte} other{# megabytes}}', $params) : Yii::t('yii', '{n} MB', $params);
            case 3:
                return $verbose ? Yii::t('yii', '{n, plural, =1{# gigabyte} other{# gigabytes}}', $params) : Yii::t('yii', '{n} GB', $params);
            case 4:
                return $verbose ? Yii::t('yii', '{n, plural, =1{# terabyte} other{# terabytes}}', $params) : Yii::t('yii', '{n} TB', $params);
            default:
                return $verbose ? Yii::t('yii', '{n, plural, =1{# petabyte} other{# petabytes}}', $params) : Yii::t('yii', '{n} PB', $params);
        }
    }
503
    
David Renty committed
504 505
    /**
     * Formats the value as the time interval between a date and now in human readable form.
506 507
     *
     * @param integer|string|DateTime|\DateInterval $value the value to be formatted. The following
David Renty committed
508 509 510 511 512
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
     * - a string that can be parsed into a UNIX timestamp via `strtotime()` or that can be passed to a DateInterval constructor.
     * - a PHP DateTime object
David Renty committed
513
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
David Renty committed
514
     *
515
     * @param integer|string|DateTime|\DateInterval $referenceTime if specified the value is used instead of now
David Renty committed
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
     * @return string the formatted result
     */
    public function asRelativeTime($value, $referenceTime = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        if ($value instanceof \DateInterval) {
            $interval = $value;
        } else {
            $timestamp = $this->normalizeDatetimeValue($value);

            if ($timestamp === false) {
                // $value is not a valid date/time value, so we try
                // to create a DateInterval with it
                try {
                    $interval = new \DateInterval($value);
Qiang Xue committed
534
                } catch (\Exception $e) {
David Renty committed
535 536 537 538 539
                    // invalid date/time and invalid interval
                    return $this->nullDisplay;
                }
            } else {
                $timezone = new \DateTimeZone($this->timeZone);
540

David Renty committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
                if ($referenceTime === null) {
                    $dateNow = new DateTime('now', $timezone);
                } else {
                    $referenceTime = $this->normalizeDatetimeValue($referenceTime);
                    $dateNow = new DateTime(null, $timezone);
                    $dateNow->setTimestamp($referenceTime);
                }

                $dateThen = new DateTime(null, $timezone);
                $dateThen->setTimestamp($timestamp);

                $interval = $dateThen->diff($dateNow);
            }
        }

        if ($interval->invert) {
            if ($interval->y >= 1) {
                return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y]);
            }
            if ($interval->m >= 1) {
                return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m]);
            }
            if ($interval->d >= 1) {
                return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d]);
            }
            if ($interval->h >= 1) {
                return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h]);
            }
            if ($interval->i >= 1) {
                return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i]);
            }

            return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s]);
        } else {
            if ($interval->y >= 1) {
                return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y]);
            }
            if ($interval->m >= 1) {
                return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m]);
            }
            if ($interval->d >= 1) {
                return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d]);
            }
            if ($interval->h >= 1) {
                return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h]);
            }
            if ($interval->i >= 1) {
                return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i]);
            }

            return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s]);
        }
    }
Qiang Xue committed
594
}