Formatter.php 53 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\i18n;
Erik_r committed
9

10
use DateInterval;
Qiang Xue committed
11
use DateTime;
12
use DateTimeInterface;
13
use DateTimeZone;
14 15
use IntlDateFormatter;
use NumberFormatter;
Carsten Brandt committed
16
use Yii;
17 18 19
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
20
use yii\helpers\FormatConverter;
Qiang Xue committed
21 22
use yii\helpers\HtmlPurifier;
use yii\helpers\Html;
23

Qiang Xue committed
24
/**
25 26
 * Formatter provides a set of commonly used data formatting methods.
 *
Qiang Xue committed
27 28 29 30
 * 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.
 *
31
 * Formatter is configured as an application component in [[\yii\base\Application]] by default.
32 33
 * You can access that instance via `Yii::$app->formatter`.
 *
34 35 36
 * The Formatter class is designed to format values according to a [[locale]]. For this feature to work
 * the [PHP intl extension](http://php.net/manual/en/book.intl.php) has to be installed.
 * Most of the methods however work also if the PHP intl extension is not installed by providing
37
 * a fallback implementation. Without intl month and day names are in English only.
38 39 40
 * Note that even if the intl extension is installed, formatting date and time values for years >=2038 or <=1901
 * on 32bit systems will fall back to the PHP implementation because intl uses a 32bit UNIX timestamp internally.
 * On a 64bit system the intl formatter is used in all cases if installed.
41 42 43 44 45 46 47
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Enrica Ruedin <e.ruedin@guggach.com>
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class Formatter extends Component
Qiang Xue committed
48
{
49 50
    /**
     * @var string the text to be displayed when formatting a `null` value.
Carsten Brandt committed
51 52
     * Defaults to `'<span class="not-set">(not set)</span>'`, where `(not set)`
     * will be translated according to [[locale]].
53 54 55 56 57
     */
    public $nullDisplay;
    /**
     * @var array the text to be displayed when formatting a boolean value. The first element corresponds
     * to the text displayed for `false`, the second element for `true`.
Carsten Brandt committed
58
     * Defaults to `['No', 'Yes']`, where `Yes` and `No`
59
     * will be translated according to [[locale]].
60 61
     */
    public $booleanFormat;
David Renty committed
62
    /**
63
     * @var string the locale ID that is used to localize the date and number formatting.
64 65
     * For number and date formatting this is only effective when the
     * [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
66 67 68
     * If not set, [[\yii\base\Application::language]] will be used.
     */
    public $locale;
69
    /**
70 71
     * @var string the time zone to use for formatting time and date values.
     *
David Renty committed
72 73
     * 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`.
74
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available time zones.
Carsten Brandt committed
75
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
76
     *
77 78
     * Note that the default time zone for input data is assumed to be UTC by default if no time zone is included in the input date value.
     * If you store your data in a different time zone in the database, you have to adjust [[defaultTimeZone]] accordingly.
David Renty committed
79 80
     */
    public $timeZone;
81 82 83 84 85 86 87
    /**
     * @var string the time zone that is assumed for input values if they do not include a time zone explicitly.
     *
     * The value must be a valid time zone identifier, e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
     * Please refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available time zones.
     *
     * It defaults to `UTC` so you only have to adjust this value if you store datetime values in another time zone in your database.
88 89
     *
     * @since 2.0.1
90 91
     */
    public $defaultTimeZone = 'UTC';
David Renty committed
92
    /**
93
     * @var string the default format string to be used to format a [[asDate()|date]].
94
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
95
     *
96
     * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
97 98
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
     * PHP [date()](http://php.net/manual/de/function.date.php)-function.
99 100 101 102 103 104 105
     *
     * For example:
     *
     * ```php
     * 'MM/dd/yyyy' // date in ICU format
     * 'php:m/d/Y' // the same date in PHP format
     * ```
David Renty committed
106
     */
107
    public $dateFormat = 'medium';
108
    /**
109
     * @var string the default format string to be used to format a [[asTime()|time]].
110
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
111
     *
112
     * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
113 114
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
     * PHP [date()](http://php.net/manual/de/function.date.php)-function.
115 116 117 118 119 120 121
     *
     * For example:
     *
     * ```php
     * 'HH:mm:ss' // time in ICU format
     * 'php:H:i:s' // the same time in PHP format
     * ```
122
     */
123
    public $timeFormat = 'medium';
David Renty committed
124
    /**
125
     * @var string the default format string to be used to format a [[asDateTime()|date and time]].
126
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
127
     *
128
     * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
129 130 131
     *
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
     * PHP [date()](http://php.net/manual/de/function.date.php)-function.
132 133 134 135 136 137 138
     *
     * For example:
     *
     * ```php
     * 'MM/dd/yyyy HH:mm:ss' // date and time in ICU format
     * 'php:m/d/Y H:i:s' // the same date and time in PHP format
     * ```
David Renty committed
139
     */
140
    public $datetimeFormat = 'medium';
David Renty committed
141 142
    /**
     * @var string the character displayed as the decimal point when formatting a number.
143
     * If not set, the decimal separator corresponding to [[locale]] will be used.
144
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is '.'.
David Renty committed
145 146 147
     */
    public $decimalSeparator;
    /**
148
     * @var string the character displayed as the thousands separator (also called grouping separator) character when formatting a number.
149
     * If not set, the thousand separator corresponding to [[locale]] will be used.
150
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is ','.
David Renty committed
151 152
     */
    public $thousandSeparator;
153 154 155 156 157 158 159 160 161
    /**
     * @var array a list of name value pairs that are passed to the
     * intl [Numberformatter::setAttribute()](http://php.net/manual/en/numberformatter.setattribute.php) method of all
     * the number formatter objects created by [[createNumberFormatter()]].
     * This property takes only effect if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
     *
     * Please refer to the [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
     * for the possible options.
     *
Carsten Brandt committed
162
     * For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
163 164 165
     *
     * ```php
     * [
Carsten Brandt committed
166 167
     *     NumberFormatter::MIN_FRACTION_DIGITS => 0,
     *     NumberFormatter::MAX_FRACTION_DIGITS => 2,
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
     * ]
     * ```
     */
    public $numberFormatterOptions = [];
    /**
     * @var array a list of name value pairs that are passed to the
     * intl [Numberformatter::setTextAttribute()](http://php.net/manual/en/numberformatter.settextattribute.php) method of all
     * the number formatter objects created by [[createNumberFormatter()]].
     * This property takes only effect if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
     *
     * Please refer to the [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformattextattribute)
     * for the possible options.
     *
     * For example to change the minus sign for negative numbers you can configure this property like the following:
     *
     * ```php
     * [
     *     NumberFormatter::NEGATIVE_PREFIX => 'MINUS',
     * ]
     * ```
     */
    public $numberFormatterTextOptions = [];
190
    /**
191
     * @var string the 3-letter ISO 4217 currency code indicating the default currency to use for [[asCurrency]].
Carsten Brandt committed
192
     * If not set, the currency code corresponding to [[locale]] will be used.
Carsten Brandt committed
193 194
     * Note that in this case the [[locale]] has to be specified with a country code, e.g. `en-US` otherwise it
     * is not possible to determine the default currency.
195 196
     */
    public $currencyCode;
David Renty committed
197
    /**
Carsten Brandt committed
198 199
     * @var array the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by [[asSize]] and [[asShortSize]].
     * Defaults to 1024.
David Renty committed
200
     */
Carsten Brandt committed
201
    public $sizeFormatBase = 1024;
David Renty committed
202

203
    /**
204
     * @var boolean whether the [PHP intl extension](http://php.net/manual/en/book.intl.php) is loaded.
205 206 207
     */
    private $_intlLoaded = false;

208

209
    /**
210
     * @inheritdoc
David Renty committed
211 212 213 214 215 216
     */
    public function init()
    {
        if ($this->timeZone === null) {
            $this->timeZone = Yii::$app->timeZone;
        }
217 218 219
        if ($this->locale === null) {
            $this->locale = Yii::$app->language;
        }
220
        if ($this->booleanFormat === null) {
221
            $this->booleanFormat = [Yii::t('yii', 'No', [], $this->locale), Yii::t('yii', 'Yes', [], $this->locale)];
David Renty committed
222 223
        }
        if ($this->nullDisplay === null) {
224
            $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)', [], $this->locale) . '</span>';
David Renty committed
225
        }
226
        $this->_intlLoaded = extension_loaded('intl');
227
        if (!$this->_intlLoaded) {
228 229 230 231 232 233
            if ($this->decimalSeparator === null) {
                $this->decimalSeparator = '.';
            }
            if ($this->thousandSeparator === null) {
                $this->thousandSeparator = ',';
            }
234
        }
David Renty committed
235 236
    }

237
    /**
David Renty committed
238 239 240 241
     * 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.
242
     * @param mixed $value the value to be formatted.
243 244 245
     * @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
246 247 248
     * 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.
     * @throws InvalidParamException if the format type is not supported by this class.
David Renty committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
     */
    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 {
267
            throw new InvalidParamException("Unknown format type: $format");
268 269 270 271
        }
    }


272
    // simple formats
273 274


David Renty committed
275 276 277
    /**
     * Formats the value as is without any formatting.
     * This method simply returns back the parameter without any format.
278
     * The only exception is a `null` value which will be formatted using [[nullDisplay]].
279 280
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
281 282 283 284 285 286 287 288
     */
    public function asRaw($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return $value;
    }
289

David Renty committed
290 291
    /**
     * Formats the value as an HTML-encoded plain text.
292
     * @param string $value the value to be formatted.
293
     * @return string the formatted result.
David Renty committed
294 295 296 297 298 299 300 301
     */
    public function asText($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return Html::encode($value);
    }
302

David Renty committed
303 304
    /**
     * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
305
     * @param string $value the value to be formatted.
306
     * @return string the formatted result.
David Renty committed
307 308 309 310 311 312 313 314 315 316 317 318 319
     */
    public function asNtext($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        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.
320
     * @param string $value the value to be formatted.
321
     * @return string the formatted result.
David Renty committed
322 323 324 325 326 327
     */
    public function asParagraphs($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
328
        return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/u', "</p>\n<p>", Html::encode($value)) . '</p>');
David Renty committed
329 330 331 332 333 334
    }

    /**
     * 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.
335
     * @param string $value the value to be formatted.
336
     * @param array|null $config the configuration for the HTMLPurifier class.
337
     * @return string the formatted result.
David Renty committed
338 339 340 341 342 343 344 345 346 347 348
     */
    public function asHtml($value, $config = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return HtmlPurifier::process($value, $config);
    }

    /**
     * Formats the value as a mailto link.
349
     * @param string $value the value to be formatted.
350
     * @param array $options the tag options in terms of name-value pairs. See [[Html::mailto()]].
351
     * @return string the formatted result.
David Renty committed
352
     */
353
    public function asEmail($value, $options = [])
David Renty committed
354 355 356 357
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
358
        return Html::mailto(Html::encode($value), $value, $options);
David Renty committed
359 360 361 362
    }

    /**
     * Formats the value as an image tag.
363
     * @param mixed $value the value to be formatted.
364
     * @param array $options the tag options in terms of name-value pairs. See [[Html::img()]].
365
     * @return string the formatted result.
David Renty committed
366
     */
367
    public function asImage($value, $options = [])
David Renty committed
368 369 370 371
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
372
        return Html::img($value, $options);
David Renty committed
373 374 375 376
    }

    /**
     * Formats the value as a hyperlink.
377
     * @param mixed $value the value to be formatted.
378
     * @param array $options the tag options in terms of name-value pairs. See [[Html::a()]].
379
     * @return string the formatted result.
David Renty committed
380
     */
381
    public function asUrl($value, $options = [])
David Renty committed
382 383 384 385 386
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $url = $value;
Carsten Brandt committed
387
        if (strpos($url, '://') === false) {
David Renty committed
388 389
            $url = 'http://' . $url;
        }
390

391
        return Html::a(Html::encode($value), $url, $options);
David Renty committed
392 393 394 395
    }

    /**
     * Formats the value as a boolean.
396 397
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
398 399 400 401 402 403 404
     * @see booleanFormat
     */
    public function asBoolean($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
405

David Renty committed
406 407
        return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
    }
408 409 410 411 412


    // date and time formats


David Renty committed
413 414 415
    /**
     * Formats the value as a date.
     * @param integer|string|DateTime $value the value to be formatted. The following
416
     * types of value are supported:
David Renty committed
417 418
     *
     * - an integer representing a UNIX timestamp
419
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
420
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
421
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
David Renty committed
422
     *
423 424 425 426 427 428 429 430 431
     * @param string $format the format used to convert the value into a date string.
     * 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).
     *
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
     * PHP [date()](http://php.net/manual/de/function.date.php)-function.
     *
432
     * @return string the formatted result.
433 434
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
David Renty committed
435 436
     * @see dateFormat
     */
437
    public function asDate($value, $format = null)
David Renty committed
438
    {
439 440
        if ($format === null) {
            $format = $this->dateFormat;
441
        }
442
        return $this->formatDateTimeValue($value, $format, 'date');
443
    }
444

David Renty committed
445 446 447
    /**
     * Formats the value as a time.
     * @param integer|string|DateTime $value the value to be formatted. The following
448
     * types of value are supported:
David Renty committed
449 450
     *
     * - an integer representing a UNIX timestamp
451
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
452
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
453
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
David Renty committed
454
     *
455
     * @param string $format the format used to convert the value into a date string.
456 457 458 459 460 461 462 463
     * If null, [[timeFormat]] 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).
     *
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
     * PHP [date()](http://php.net/manual/de/function.date.php)-function.
     *
464
     * @return string the formatted result.
465 466
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
David Renty committed
467 468
     * @see timeFormat
     */
469
    public function asTime($value, $format = null)
David Renty committed
470
    {
471 472
        if ($format === null) {
            $format = $this->timeFormat;
David Renty committed
473
        }
474 475 476 477 478 479 480 481 482
        return $this->formatDateTimeValue($value, $format, 'time');
    }

    /**
     * Formats the value as a datetime.
     * @param integer|string|DateTime $value the value to be formatted. The following
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
483
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
484
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
485
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
486 487 488 489 490 491 492 493 494 495
     *
     * @param string $format the format used to convert the value into a date string.
     * 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).
     *
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
     * PHP [date()](http://php.net/manual/de/function.date.php)-function.
     *
496
     * @return string the formatted result.
497 498
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
499 500 501 502 503 504
     * @see datetimeFormat
     */
    public function asDatetime($value, $format = null)
    {
        if ($format === null) {
            $format = $this->datetimeFormat;
505
        }
506 507 508
        return $this->formatDateTimeValue($value, $format, 'datetime');
    }

509 510 511
    /**
     * @var array map of short format names to IntlDateFormatter constant values.
     */
512 513 514 515 516 517 518 519
    private $_dateFormats = [
        'short'  => 3, // IntlDateFormatter::SHORT,
        'medium' => 2, // IntlDateFormatter::MEDIUM,
        'long'   => 1, // IntlDateFormatter::LONG,
        'full'   => 0, // IntlDateFormatter::FULL,
    ];

    /**
520 521 522 523 524
     * @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 to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
525
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
526 527
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
528
     * @param string $format the format used to convert the value into a date string.
529 530
     * @param string $type 'date', 'time', or 'datetime'.
     * @throws InvalidConfigException if the date format is invalid.
531
     * @return string the formatted result.
532 533 534
     */
    private function formatDateTimeValue($value, $format, $type)
    {
535
        $timeZone = $this->timeZone;
536
        // avoid time zone conversion for date-only values
537 538 539 540 541
        if ($type === 'date') {
            list($timestamp, $hasTimeInfo) = $this->normalizeDatetimeValue($value, true);
            if (!$hasTimeInfo) {
                $timeZone = $this->defaultTimeZone;
            }
542
        } else {
543 544 545 546
            $timestamp = $this->normalizeDatetimeValue($value);
        }
        if ($timestamp === null) {
            return $this->nullDisplay;
547 548
        }

549 550 551
        // intl does not work with dates >=2038 or <=1901 on 32bit machines, fall back to PHP
        $year = $timestamp->format('Y');
        if ($this->_intlLoaded && !(PHP_INT_SIZE == 4 && ($year <= 1901 || $year >= 2038))) {
552
            if (strncmp($format, 'php:', 4) === 0) {
553 554
                $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
            }
555 556
            if (isset($this->_dateFormats[$format])) {
                if ($type === 'date') {
557
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $timeZone);
558
                } elseif ($type === 'time') {
559
                    $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $timeZone);
560
                } else {
561
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $timeZone);
562 563
                }
            } else {
564
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $timeZone, null, $format);
565
            }
566 567 568
            if ($formatter === null) {
                throw new InvalidConfigException(intl_get_error_message());
            }
569 570 571 572
            // make IntlDateFormatter work with DateTimeImmutable
            if ($timestamp instanceof \DateTimeImmutable) {
                $timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone());
            }
573
            return $formatter->format($timestamp);
574
        } else {
575
            if (strncmp($format, 'php:', 4) === 0) {
576
                $format = substr($format, 4);
577
            } else {
578
                $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
579
            }
580
            if ($timeZone != null) {
581 582 583 584 585
                if ($timestamp instanceof \DateTimeImmutable) {
                    $timestamp = $timestamp->setTimezone(new DateTimeZone($timeZone));
                } else {
                    $timestamp->setTimezone(new DateTimeZone($timeZone));
                }
586 587
            }
            return $timestamp->format($format);
588 589
        }
    }
590

David Renty committed
591
    /**
592
     * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
Kartik Visweswaran committed
593
     *
594 595 596 597 598
     * @param integer|string|DateTime $value the datetime value to be normalized. The following
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
599
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
600 601
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
602 603 604 605 606 607 608 609
     * @param boolean $checkTimeInfo whether to also check if the date/time value has some time information attached.
     * Defaults to `false`. If `true`, the method will then return an array with the first element being the normalized
     * timestamp and the second a boolean indicating whether the timestamp has time information or it is just a date value.
     * This parameter is available since version 2.0.1.
     * @return DateTime|array the normalized datetime value.
     * Since version 2.0.1 this may also return an array if `$checkTimeInfo` is true.
     * The first element of the array is the normalized timestamp and the second is a boolean indicating whether
     * the timestamp has time information or it is just a date value.
610
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
David Renty committed
611
     */
612
    protected function normalizeDatetimeValue($value, $checkTimeInfo = false)
David Renty committed
613
    {
614
        // checking for DateTime and DateTimeInterface is not redundant, DateTimeInterface is only in PHP>5.5
615
        if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
616
            // skip any processing
617
            return $checkTimeInfo ? [$value, true] : $value;
618 619 620 621 622
        }
        if (empty($value)) {
            $value = 0;
        }
        try {
623
            if (is_numeric($value)) { // process as unix timestamp, which is always in UTC
624
                if (($timestamp = DateTime::createFromFormat('U', $value, new DateTimeZone('UTC'))) === false) {
625 626
                    throw new InvalidParamException("Failed to parse '$value' as a UNIX timestamp.");
                }
627 628 629 630 631
                return $checkTimeInfo ? [$timestamp, true] : $timestamp;
            } elseif (($timestamp = DateTime::createFromFormat('Y-m-d', $value, new DateTimeZone($this->defaultTimeZone))) !== false) { // try Y-m-d format (support invalid dates like 2012-13-01)
                return $checkTimeInfo ? [$timestamp, false] : $timestamp;
            } elseif (($timestamp = DateTime::createFromFormat('Y-m-d H:i:s', $value, new DateTimeZone($this->defaultTimeZone))) !== false) { // try Y-m-d H:i:s format (support invalid dates like 2012-13-01 12:63:12)
                return $checkTimeInfo ? [$timestamp, true] : $timestamp;
632
            }
633
            // finally try to create a DateTime object with the value
634 635 636 637 638 639 640
            if ($checkTimeInfo) {
                $timestamp = new DateTime($value, new DateTimeZone($this->defaultTimeZone));
                $info = date_parse($value);
                return [$timestamp, !($info['hour'] === false && $info['minute'] === false && $info['second'] === false)];
            } else {
                return new DateTime($value, new DateTimeZone($this->defaultTimeZone));
            }
641 642 643
        } catch(\Exception $e) {
            throw new InvalidParamException("'$value' is not a valid date time value: " . $e->getMessage()
                . "\n" . print_r(DateTime::getLastErrors(), true), $e->getCode(), $e);
644 645 646
        }
    }

647
    /**
648
     * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
649
     * @param integer|string|DateTime $value the value to be formatted. The following
650 651 652
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
653
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
654
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
655
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
656 657
     *
     * @return string the formatted result.
658 659 660 661 662 663
     */
    public function asTimestamp($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
664 665
        $timestamp = $this->normalizeDatetimeValue($value);
        return number_format($timestamp->format('U'), 0, '.', '');
666 667 668 669 670
    }

    /**
     * Formats the value as the time interval between a date and now in human readable form.
     *
671 672 673 674 675 676 677
     * This method can be used in three different ways:
     *
     * 1. Using a timestamp that is relative to `now`.
     * 2. Using a timestamp that is relative to the `$referenceTime`.
     * 3. Using a `DateInterval` object.
     *
     * @param integer|string|DateTime|DateInterval $value the value to be formatted. The following
678 679 680
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
681
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
682
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
683
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
684 685
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
     *
686 687
     * @param integer|string|DateTime $referenceTime if specified the value is used as a reference time instead of `now`
     * when `$value` is not a `DateInterval` object.
688
     * @return string the formatted result.
689
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
690 691 692 693 694 695 696
     */
    public function asRelativeTime($value, $referenceTime = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

697
        if ($value instanceof DateInterval) {
698 699 700 701 702 703 704 705
            $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 {
706
                    $interval = new DateInterval($value);
707 708 709 710 711
                } catch (\Exception $e) {
                    // invalid date/time and invalid interval
                    return $this->nullDisplay;
                }
            } else {
712
                $timeZone = new DateTimeZone($this->timeZone);
713 714

                if ($referenceTime === null) {
715
                    $dateNow = new DateTime('now', $timeZone);
716
                } else {
717
                    $dateNow = $this->normalizeDatetimeValue($referenceTime);
718
                    $dateNow->setTimezone($timeZone);
719 720
                }

721
                $dateThen = $timestamp->setTimezone($timeZone);
722 723 724 725 726 727 728

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

        if ($interval->invert) {
            if ($interval->y >= 1) {
729
                return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->locale);
730 731
            }
            if ($interval->m >= 1) {
732
                return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->locale);
733 734
            }
            if ($interval->d >= 1) {
735
                return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->locale);
736 737
            }
            if ($interval->h >= 1) {
738
                return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->locale);
739 740
            }
            if ($interval->i >= 1) {
741
                return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
742
            }
743 744 745
            if ($interval->s == 0) {
                return Yii::t('yii', 'just now', [], $this->locale);
            }
746
            return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
747 748
        } else {
            if ($interval->y >= 1) {
749
                return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale);
750 751
            }
            if ($interval->m >= 1) {
752
                return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->locale);
753 754
            }
            if ($interval->d >= 1) {
755
                return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->locale);
756 757
            }
            if ($interval->h >= 1) {
758
                return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->locale);
759 760
            }
            if ($interval->i >= 1) {
761
                return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->locale);
762
            }
763 764 765
            if ($interval->s == 0) {
                return Yii::t('yii', 'just now', [], $this->locale);
            }
766
            return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
767 768 769
        }
    }

770 771 772 773

    // number formats


David Renty committed
774
    /**
775 776 777 778 779 780
     * Formats the value as an integer number by removing any decimal digits without rounding.
     *
     * @param mixed $value the value to be formatted.
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
     * @return string the formatted result.
781
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
782
     */
783
    public function asInteger($value, $options = [], $textOptions = [])
784
    {
David Renty committed
785 786 787
        if ($value === null) {
            return $this->nullDisplay;
        }
788 789
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded) {
790
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
791
            $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
792
            return $f->format($value, NumberFormatter::TYPE_INT64);
David Renty committed
793
        } else {
794
            return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
795 796
        }
    }
797 798

    /**
799 800
     * Formats the value as a decimal number.
     *
801
     * Property [[decimalSeparator]] will be used to represent the decimal point. The
802 803
     * value is rounded automatically to the defined decimal digits.
     *
804
     * @param mixed $value the value to be formatted.
805 806
     * @param integer $decimals the number of digits after the decimal point. If not given the number of digits is determined from the
     * [[locale]] and if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available defaults to `2`.
807 808 809
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
     * @return string the formatted result.
810
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
811
     * @see decimalSeparator
812
     * @see thousandSeparator
David Renty committed
813
     */
814
    public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
815 816 817 818
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
819
        $value = $this->normalizeNumericValue($value);
820

821
        if ($this->_intlLoaded) {
822
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
823
            return $f->format($value);
David Renty committed
824
        } else {
825 826 827
            if ($decimals === null){
                $decimals = 2;
            }
828
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
829 830 831
        }
    }

832

David Renty committed
833
    /**
834
     * Formats the value as a percent number with "%" sign.
835 836 837 838 839
     *
     * @param mixed $value the value to be formatted. It must be a factor e.g. `0.75` will result in `75%`.
     * @param integer $decimals the number of digits after the decimal point.
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
840
     * @return string the formatted result.
841
     * @throws InvalidParamException if the input value is not numeric.
842
     */
843
    public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
844 845 846 847
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
848
        $value = $this->normalizeNumericValue($value);
849

850
        if ($this->_intlLoaded) {
851
            $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
852 853
            return $f->format($value);
        } else {
854 855 856
            if ($decimals === null){
                $decimals = 0;
            }
857
            $value = $value * 100;
858
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
859 860
        }
    }
861 862

    /**
863
     * Formats the value as a scientific number.
864
     *
865 866 867 868
     * @param mixed $value the value to be formatted.
     * @param integer $decimals the number of digits after the decimal point.
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
869
     * @return string the formatted result.
870
     * @throws InvalidParamException if the input value is not numeric.
871
     */
872
    public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
873
    {
David Renty committed
874 875 876
        if ($value === null) {
            return $this->nullDisplay;
        }
877
        $value = $this->normalizeNumericValue($value);
878

879
        if ($this->_intlLoaded){
880
            $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
881 882
            return $f->format($value);
        } else {
883
            if ($decimals !== null) {
884
                return sprintf("%.{$decimals}E", $value);
885 886 887
            } else {
                return sprintf("%.E", $value);
            }
888
        }
David Renty committed
889
    }
890 891

    /**
892
     * Formats the value as a currency number.
893 894 895 896
     *
     * This function does not requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed
     * to work but it is highly recommended to install it to get good formatting results.
     *
897
     * @param mixed $value the value to be formatted.
898
     * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
Carsten Brandt committed
899
     * If null, [[currencyCode]] will be used.
900 901
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
902
     * @return string the formatted result.
903
     * @throws InvalidParamException if the input value is not numeric.
904
     * @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
905
     */
906
    public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
907 908 909 910
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
911
        $value = $this->normalizeNumericValue($value);
912 913

        if ($this->_intlLoaded) {
914
            $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
Carsten Brandt committed
915 916 917 918 919 920 921
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    $currency = $formatter->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL);
                } else {
                    $currency = $this->currencyCode;
                }
            }
922
            return $formatter->formatCurrency($value, $currency);
923
        } else {
Carsten Brandt committed
924 925 926 927 928 929
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    throw new InvalidConfigException('The default currency code for the formatter is not defined.');
                }
                $currency = $this->currencyCode;
            }
930
            return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
931 932
        }
    }
933

934 935
    /**
     * Formats the value as a number spellout.
936 937 938
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
939 940 941
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
942
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
943 944 945 946 947 948 949 950 951 952 953
     */
    public function asSpellout($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded){
            $f = $this->createNumberFormatter(NumberFormatter::SPELLOUT);
            return $f->format($value);
        } else {
954
            throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
955 956
        }
    }
957

958 959
    /**
     * Formats the value as a ordinal value of a number.
960 961 962
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
963 964 965
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
966
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
967 968 969 970 971 972 973 974 975 976 977
     */
    public function asOrdinal($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded){
            $f = $this->createNumberFormatter(NumberFormatter::ORDINAL);
            return $f->format($value);
        } else {
978
            throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
979 980
        }
    }
981

David Renty committed
982
    /**
Carsten Brandt committed
983 984 985 986 987 988 989 990 991 992 993
     * Formats the value in bytes as a size in human readable form for example `12 KB`.
     *
     * This is the short form of [[asSize]].
     *
     * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...)
     * are used in the formatting result.
     *
     * @param integer $value value in bytes to be formatted.
     * @param integer $decimals the number of digits after the decimal point.
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
994
     * @return string the formatted result.
995
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
996
     * @see sizeFormat
Carsten Brandt committed
997
     * @see asSize
David Renty committed
998
     */
Carsten Brandt committed
999
    public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
1000
    {
1001 1002 1003
        if ($value === null) {
            return $this->nullDisplay;
        }
Carsten Brandt committed
1004 1005 1006 1007 1008

        list($params, $position) = $this->formatSizeNumber($value, $decimals, $options, $textOptions);

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1009 1010 1011 1012 1013 1014
                case 0:  return Yii::t('yii', '{nFormatted} B', $params, $this->locale);
                case 1:  return Yii::t('yii', '{nFormatted} KiB', $params, $this->locale);
                case 2:  return Yii::t('yii', '{nFormatted} MiB', $params, $this->locale);
                case 3:  return Yii::t('yii', '{nFormatted} GiB', $params, $this->locale);
                case 4:  return Yii::t('yii', '{nFormatted} TiB', $params, $this->locale);
                default: return Yii::t('yii', '{nFormatted} PiB', $params, $this->locale);
David Renty committed
1015
            }
Carsten Brandt committed
1016 1017
        } else {
            switch ($position) {
1018 1019 1020 1021 1022 1023
                case 0:  return Yii::t('yii', '{nFormatted} B', $params, $this->locale);
                case 1:  return Yii::t('yii', '{nFormatted} KB', $params, $this->locale);
                case 2:  return Yii::t('yii', '{nFormatted} MB', $params, $this->locale);
                case 3:  return Yii::t('yii', '{nFormatted} GB', $params, $this->locale);
                case 4:  return Yii::t('yii', '{nFormatted} TB', $params, $this->locale);
                default: return Yii::t('yii', '{nFormatted} PB', $params, $this->locale);
Carsten Brandt committed
1024 1025 1026
            }
        }
    }
David Renty committed
1027

Carsten Brandt committed
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    /**
     * Formats the value in bytes as a size in human readable form, for example `12 kilobytes`.
     *
     * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...)
     * are used in the formatting result.
     *
     * @param integer $value value in bytes to be formatted.
     * @param integer $decimals the number of digits after the decimal point.
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
     * @see sizeFormat
     * @see asShortSize
     */
    public function asSize($value, $decimals = null, $options = [], $textOptions = [])
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        list($params, $position) = $this->formatSizeNumber($value, $decimals, $options, $textOptions);
1050

Carsten Brandt committed
1051 1052
        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1053 1054 1055 1056 1057 1058
                case 0:  return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->locale);
                case 1:  return Yii::t('yii', '{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}', $params, $this->locale);
                case 2:  return Yii::t('yii', '{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}', $params, $this->locale);
                case 3:  return Yii::t('yii', '{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}', $params, $this->locale);
                case 4:  return Yii::t('yii', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}', $params, $this->locale);
                default: return Yii::t('yii', '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}', $params, $this->locale);
Carsten Brandt committed
1059 1060
            }
        } else {
1061
            switch ($position) {
1062 1063 1064 1065 1066 1067
                case 0:  return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->locale);
                case 1:  return Yii::t('yii', '{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}', $params, $this->locale);
                case 2:  return Yii::t('yii', '{nFormatted} {n, plural, =1{megabyte} other{megabytes}}', $params, $this->locale);
                case 3:  return Yii::t('yii', '{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}', $params, $this->locale);
                case 4:  return Yii::t('yii', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}', $params, $this->locale);
                default: return Yii::t('yii', '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}', $params, $this->locale);
1068 1069
            }
        }
Carsten Brandt committed
1070 1071
    }

1072 1073 1074 1075 1076 1077 1078 1079 1080

    /**
     * Given the value in bytes formats number part of the human readable form.
     *
     * @param string|integer|float $value value in bytes to be formatted.
     * @param integer $decimals the number of digits after the decimal point
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
     * @return array [parameters for Yii::t containing formatted number, internal position of size unit]
1081
     * @throws InvalidParamException if the input value is not numeric.
1082
     */
Carsten Brandt committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    private function formatSizeNumber($value, $decimals, $options, $textOptions)
    {
        if (is_string($value) && is_numeric($value)) {
            $value = (int) $value;
        }
        if (!is_numeric($value)) {
            throw new InvalidParamException("'$value' is not a numeric value.");
        }

        $position = 0;
        do {
            if ($value < $this->sizeFormatBase) {
                break;
            }
            $value = $value / $this->sizeFormatBase;
            $position++;
        } while ($position < 5);
1100

Carsten Brandt committed
1101 1102 1103 1104 1105
        // no decimals for bytes
        if ($position === 0) {
            $decimals = 0;
        } elseif ($decimals !== null) {
            $value = round($value, $decimals);
David Renty committed
1106
        }
Carsten Brandt committed
1107 1108 1109
        // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
        $oldThousandSeparator = $this->thousandSeparator;
        $this->thousandSeparator = '';
1110 1111 1112
        if ($this->_intlLoaded) {
            $options[NumberFormatter::GROUPING_USED] = false;
        }
Carsten Brandt committed
1113
        // format the size value
1114 1115 1116 1117 1118 1119
        $params = [
            // this is the unformatted number used for the plural rule
            'n' => $value,
            // this is the formatted number used for display
            'nFormatted' => $this->asDecimal($value, $decimals, $options, $textOptions),
        ];
Carsten Brandt committed
1120 1121 1122
        $this->thousandSeparator = $oldThousandSeparator;

        return [$params, $position];
David Renty committed
1123 1124
    }

1125 1126 1127 1128 1129
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1130 1131
    protected function normalizeNumericValue($value)
    {
1132 1133 1134
        if (empty($value)) {
            return 0;
        }
1135 1136 1137 1138 1139 1140 1141 1142 1143
        if (is_string($value) && is_numeric($value)) {
            $value = (float) $value;
        }
        if (!is_numeric($value)) {
            throw new InvalidParamException("'$value' is not a numeric value.");
        }
        return $value;
    }

1144 1145
    /**
     * Creates a number formatter based on the given type and format.
1146
     *
Alexander Mohorev committed
1147
     * You may override this method to create a number formatter based on patterns.
1148
     *
Carsten Brandt committed
1149
     * @param integer $style the type of the number formatter.
1150 1151
     * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
     *          ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
Carsten Brandt committed
1152 1153 1154
     * @param integer $decimals the number of digits after the decimal point.
     * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
     * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
1155 1156
     * @return NumberFormatter the created formatter instance
     */
1157
    protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
1158
    {
1159 1160 1161
        $formatter = new NumberFormatter($this->locale, $style);

        if ($this->decimalSeparator !== null) {
1162
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1163 1164
        }
        if ($this->thousandSeparator !== null) {
1165
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1166
        }
1167

1168 1169 1170 1171
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1172

Carsten Brandt committed
1173 1174 1175 1176
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1177 1178
            $formatter->setTextAttribute($name, $attribute);
        }
1179 1180 1181 1182 1183 1184
        foreach ($this->numberFormatterOptions as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
1185 1186
        return $formatter;
    }
Qiang Xue committed
1187
}