Formatter.php 52.5 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 41 42 43 44
 *
 * @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
45
{
46 47
    /**
     * @var string the text to be displayed when formatting a `null` value.
Carsten Brandt committed
48 49
     * Defaults to `'<span class="not-set">(not set)</span>'`, where `(not set)`
     * will be translated according to [[locale]].
50 51 52 53 54
     */
    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
55
     * Defaults to `['No', 'Yes']`, where `Yes` and `No`
56
     * will be translated according to [[locale]].
57 58
     */
    public $booleanFormat;
David Renty committed
59
    /**
60
     * @var string the locale ID that is used to localize the date and number formatting.
61 62
     * For number and date formatting this is only effective when the
     * [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
63 64 65
     * If not set, [[\yii\base\Application::language]] will be used.
     */
    public $locale;
66
    /**
67 68
     * @var string the time zone to use for formatting time and date values.
     *
David Renty committed
69 70
     * 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`.
71
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available time zones.
Carsten Brandt committed
72
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
73
     *
74 75
     * 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
76 77
     */
    public $timeZone;
78 79 80 81 82 83 84
    /**
     * @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.
85 86
     *
     * @since 2.0.1
87 88
     */
    public $defaultTimeZone = 'UTC';
David Renty committed
89
    /**
90
     * @var string the default format string to be used to format a [[asDate()|date]].
91
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
92
     *
93
     * 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).
94 95
     * 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.
96 97 98 99 100 101 102
     *
     * For example:
     *
     * ```php
     * 'MM/dd/yyyy' // date in ICU format
     * 'php:m/d/Y' // the same date in PHP format
     * ```
David Renty committed
103
     */
104
    public $dateFormat = 'medium';
105
    /**
106
     * @var string the default format string to be used to format a [[asTime()|time]].
107
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
108
     *
109
     * 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).
110 111
     * 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.
112 113 114 115 116 117 118
     *
     * For example:
     *
     * ```php
     * 'HH:mm:ss' // time in ICU format
     * 'php:H:i:s' // the same time in PHP format
     * ```
119
     */
120
    public $timeFormat = 'medium';
David Renty committed
121
    /**
122
     * @var string the default format string to be used to format a [[asDateTime()|date and time]].
123
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
124
     *
125
     * 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).
126 127 128
     *
     * 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.
129 130 131 132 133 134 135
     *
     * 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
136
     */
137
    public $datetimeFormat = 'medium';
David Renty committed
138 139
    /**
     * @var string the character displayed as the decimal point when formatting a number.
140
     * If not set, the decimal separator corresponding to [[locale]] will be used.
141
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is '.'.
David Renty committed
142 143 144
     */
    public $decimalSeparator;
    /**
145
     * @var string the character displayed as the thousands separator (also called grouping separator) character when formatting a number.
146
     * If not set, the thousand separator corresponding to [[locale]] will be used.
147
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is ','.
David Renty committed
148 149
     */
    public $thousandSeparator;
150 151 152 153 154 155 156 157 158
    /**
     * @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
159
     * For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
160 161 162
     *
     * ```php
     * [
Carsten Brandt committed
163 164
     *     NumberFormatter::MIN_FRACTION_DIGITS => 0,
     *     NumberFormatter::MAX_FRACTION_DIGITS => 2,
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
     * ]
     * ```
     */
    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 = [];
187
    /**
188
     * @var string the 3-letter ISO 4217 currency code indicating the default currency to use for [[asCurrency]].
Carsten Brandt committed
189
     * If not set, the currency code corresponding to [[locale]] will be used.
Carsten Brandt committed
190 191
     * 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.
192 193
     */
    public $currencyCode;
David Renty committed
194
    /**
Carsten Brandt committed
195 196
     * @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
197
     */
Carsten Brandt committed
198
    public $sizeFormatBase = 1024;
David Renty committed
199

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

205

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

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


269
    // simple formats
270 271


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

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

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

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

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

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

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

388
        return Html::a(Html::encode($value), $url, $options);
David Renty committed
389 390 391 392
    }

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

David Renty committed
403 404
        return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
    }
405 406 407 408 409


    // date and time formats


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

David Renty committed
442 443 444
    /**
     * Formats the value as a time.
     * @param integer|string|DateTime $value the value to be formatted. The following
445
     * types of value are supported:
David Renty committed
446 447
     *
     * - an integer representing a UNIX timestamp
448
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
449
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
450
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
David Renty committed
451
     *
452
     * @param string $format the format used to convert the value into a date string.
453 454 455 456 457 458 459 460
     * 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.
     *
461
     * @return string the formatted result.
462 463
     * @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
464 465
     * @see timeFormat
     */
466
    public function asTime($value, $format = null)
David Renty committed
467
    {
468 469
        if ($format === null) {
            $format = $this->timeFormat;
David Renty committed
470
        }
471 472 473 474 475 476 477 478 479
        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
480
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
481
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
482
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
483 484 485 486 487 488 489 490 491 492
     *
     * @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.
     *
493
     * @return string the formatted result.
494 495
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
496 497 498 499 500 501
     * @see datetimeFormat
     */
    public function asDatetime($value, $format = null)
    {
        if ($format === null) {
            $format = $this->datetimeFormat;
502
        }
503 504 505
        return $this->formatDateTimeValue($value, $format, 'datetime');
    }

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

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

546
        if ($this->_intlLoaded) {
547
            if (strncmp($format, 'php:', 4) === 0) {
548 549
                $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
            }
550 551
            if (isset($this->_dateFormats[$format])) {
                if ($type === 'date') {
552
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $timeZone);
553
                } elseif ($type === 'time') {
554
                    $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $timeZone);
555
                } else {
556
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $timeZone);
557 558
                }
            } else {
559
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $timeZone, null, $format);
560
            }
561 562 563
            if ($formatter === null) {
                throw new InvalidConfigException(intl_get_error_message());
            }
564 565 566 567
            // make IntlDateFormatter work with DateTimeImmutable
            if ($timestamp instanceof \DateTimeImmutable) {
                $timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone());
            }
568
            return $formatter->format($timestamp);
569
        } else {
570
            if (strncmp($format, 'php:', 4) === 0) {
571
                $format = substr($format, 4);
572
            } else {
573
                $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
574
            }
575
            if ($timeZone != null) {
576 577 578 579 580
                if ($timestamp instanceof \DateTimeImmutable) {
                    $timestamp = $timestamp->setTimezone(new DateTimeZone($timeZone));
                } else {
                    $timestamp->setTimezone(new DateTimeZone($timeZone));
                }
581 582
            }
            return $timestamp->format($format);
583 584
        }
    }
585

David Renty committed
586
    /**
587
     * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
Kartik Visweswaran committed
588
     *
589 590 591 592 593
     * @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).
594
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
595 596
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
597 598 599 600 601 602 603 604
     * @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.
605
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
David Renty committed
606
     */
607
    protected function normalizeDatetimeValue($value, $checkTimeInfo = false)
David Renty committed
608
    {
609
        // checking for DateTime and DateTimeInterface is not redundant, DateTimeInterface is only in PHP>5.5
610
        if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
611
            // skip any processing
612
            return $checkTimeInfo ? [$value, true] : $value;
613 614 615 616 617
        }
        if (empty($value)) {
            $value = 0;
        }
        try {
618
            if (is_numeric($value)) { // process as unix timestamp, which is always in UTC
619
                if (($timestamp = DateTime::createFromFormat('U', $value, new DateTimeZone('UTC'))) === false) {
620 621
                    throw new InvalidParamException("Failed to parse '$value' as a UNIX timestamp.");
                }
622 623 624 625 626
                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;
627
            }
628
            // finally try to create a DateTime object with the value
629 630 631 632 633 634 635
            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));
            }
636 637 638
        } 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);
639 640 641
        }
    }

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

    /**
     * Formats the value as the time interval between a date and now in human readable form.
     *
666 667 668 669 670 671 672
     * 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
673 674 675
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
676
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
677
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
678
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
679 680
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
     *
681 682
     * @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.
683
     * @return string the formatted result.
684
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
685 686 687 688 689 690 691
     */
    public function asRelativeTime($value, $referenceTime = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

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

                if ($referenceTime === null) {
710
                    $dateNow = new DateTime('now', $timeZone);
711
                } else {
712
                    $dateNow = $this->normalizeDatetimeValue($referenceTime);
713
                    $dateNow->setTimezone($timeZone);
714 715
                }

716
                $dateThen = $timestamp->setTimezone($timeZone);
717 718 719 720 721 722 723

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

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

765 766 767 768

    // number formats


David Renty committed
769
    /**
770 771 772 773 774 775
     * 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.
776
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
777
     */
778
    public function asInteger($value, $options = [], $textOptions = [])
779
    {
David Renty committed
780 781 782
        if ($value === null) {
            return $this->nullDisplay;
        }
783 784
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded) {
785
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
786
            $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
787
            return $f->format($value, NumberFormatter::TYPE_INT64);
David Renty committed
788
        } else {
789
            return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
790 791
        }
    }
792 793

    /**
794 795
     * Formats the value as a decimal number.
     *
796
     * Property [[decimalSeparator]] will be used to represent the decimal point. The
797 798
     * value is rounded automatically to the defined decimal digits.
     *
799
     * @param mixed $value the value to be formatted.
800 801
     * @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`.
802 803 804
     * @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.
805
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
806
     * @see decimalSeparator
807
     * @see thousandSeparator
David Renty committed
808
     */
809
    public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
810 811 812 813
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
814
        $value = $this->normalizeNumericValue($value);
815

816
        if ($this->_intlLoaded) {
817
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
818
            return $f->format($value);
David Renty committed
819
        } else {
820 821 822
            if ($decimals === null){
                $decimals = 2;
            }
823
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
824 825 826
        }
    }

827

David Renty committed
828
    /**
829
     * Formats the value as a percent number with "%" sign.
830 831 832 833 834
     *
     * @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]].
835
     * @return string the formatted result.
836
     * @throws InvalidParamException if the input value is not numeric.
837
     */
838
    public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
839 840 841 842
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
843
        $value = $this->normalizeNumericValue($value);
844

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

    /**
858
     * Formats the value as a scientific number.
859
     *
860 861 862 863
     * @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]].
864
     * @return string the formatted result.
865
     * @throws InvalidParamException if the input value is not numeric.
866
     */
867
    public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
868
    {
David Renty committed
869 870 871
        if ($value === null) {
            return $this->nullDisplay;
        }
872
        $value = $this->normalizeNumericValue($value);
873

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

    /**
887
     * Formats the value as a currency number.
888 889 890 891
     *
     * 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.
     *
892
     * @param mixed $value the value to be formatted.
893
     * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
Carsten Brandt committed
894
     * If null, [[currencyCode]] will be used.
895 896
     * @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]].
897
     * @return string the formatted result.
898
     * @throws InvalidParamException if the input value is not numeric.
899
     * @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
900
     */
901
    public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
902 903 904 905
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
906
        $value = $this->normalizeNumericValue($value);
907 908

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

929 930
    /**
     * Formats the value as a number spellout.
931 932 933
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
934 935 936
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
937
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
938 939 940 941 942 943 944 945 946 947 948
     */
    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 {
949
            throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
950 951
        }
    }
952

953 954
    /**
     * Formats the value as a ordinal value of a number.
955 956 957
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
958 959 960
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
961
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
962 963 964 965 966 967 968 969 970 971 972
     */
    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 {
973
            throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
974 975
        }
    }
976

David Renty committed
977
    /**
Carsten Brandt committed
978 979 980 981 982 983 984 985 986 987 988
     * 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]].
989
     * @return string the formatted result.
990
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
991
     * @see sizeFormat
Carsten Brandt committed
992
     * @see asSize
David Renty committed
993
     */
Carsten Brandt committed
994
    public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
995
    {
996 997 998
        if ($value === null) {
            return $this->nullDisplay;
        }
Carsten Brandt committed
999 1000 1001 1002 1003

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

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1004 1005 1006 1007 1008 1009
                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
1010
            }
Carsten Brandt committed
1011 1012
        } else {
            switch ($position) {
1013 1014 1015 1016 1017 1018
                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
1019 1020 1021
            }
        }
    }
David Renty committed
1022

Carsten Brandt committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    /**
     * 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);
1045

Carsten Brandt committed
1046 1047
        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1048 1049 1050 1051 1052 1053
                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
1054 1055
            }
        } else {
1056
            switch ($position) {
1057 1058 1059 1060 1061 1062
                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);
1063 1064
            }
        }
Carsten Brandt committed
1065 1066
    }

1067 1068 1069 1070 1071 1072 1073 1074 1075

    /**
     * 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]
1076
     * @throws InvalidParamException if the input value is not numeric.
1077
     */
Carsten Brandt committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    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);
1095

Carsten Brandt committed
1096 1097 1098 1099 1100
        // no decimals for bytes
        if ($position === 0) {
            $decimals = 0;
        } elseif ($decimals !== null) {
            $value = round($value, $decimals);
David Renty committed
1101
        }
Carsten Brandt committed
1102 1103 1104
        // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
        $oldThousandSeparator = $this->thousandSeparator;
        $this->thousandSeparator = '';
1105 1106 1107
        if ($this->_intlLoaded) {
            $options[NumberFormatter::GROUPING_USED] = false;
        }
Carsten Brandt committed
1108
        // format the size value
1109 1110 1111 1112 1113 1114
        $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
1115 1116 1117
        $this->thousandSeparator = $oldThousandSeparator;

        return [$params, $position];
David Renty committed
1118 1119
    }

1120 1121 1122 1123 1124
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1125 1126
    protected function normalizeNumericValue($value)
    {
1127 1128 1129
        if (empty($value)) {
            return 0;
        }
1130 1131 1132 1133 1134 1135 1136 1137 1138
        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;
    }

1139 1140
    /**
     * Creates a number formatter based on the given type and format.
1141
     *
Alexander Mohorev committed
1142
     * You may override this method to create a number formatter based on patterns.
1143
     *
Carsten Brandt committed
1144
     * @param integer $style the type of the number formatter.
1145 1146
     * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
     *          ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
Carsten Brandt committed
1147 1148 1149
     * @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]].
1150 1151
     * @return NumberFormatter the created formatter instance
     */
1152
    protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
1153
    {
1154 1155 1156
        $formatter = new NumberFormatter($this->locale, $style);

        if ($this->decimalSeparator !== null) {
1157
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1158 1159
        }
        if ($this->thousandSeparator !== null) {
1160
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1161
        }
1162

1163 1164 1165 1166
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1167

Carsten Brandt committed
1168 1169 1170 1171
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1172 1173
            $formatter->setTextAttribute($name, $attribute);
        }
1174 1175 1176 1177 1178 1179
        foreach ($this->numberFormatterOptions as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
1180 1181
        return $formatter;
    }
Qiang Xue committed
1182
}