Formatter.php 52.1 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
            return $formatter->format($timestamp);
565
        } else {
566
            if (strncmp($format, 'php:', 4) === 0) {
567
                $format = substr($format, 4);
568
            } else {
569
                $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
570
            }
571 572
            if ($timeZone != null) {
                $timestamp->setTimezone(new DateTimeZone($timeZone));
573 574
            }
            return $timestamp->format($format);
575 576
        }
    }
577

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

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

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

684
        if ($value instanceof DateInterval) {
685 686 687 688 689 690 691 692
            $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 {
693
                    $interval = new DateInterval($value);
694 695 696 697 698
                } catch (\Exception $e) {
                    // invalid date/time and invalid interval
                    return $this->nullDisplay;
                }
            } else {
699
                $timeZone = new DateTimeZone($this->timeZone);
700 701

                if ($referenceTime === null) {
702
                    $dateNow = new DateTime('now', $timeZone);
703
                } else {
704
                    $dateNow = $this->normalizeDatetimeValue($referenceTime);
705
                    $dateNow->setTimezone($timeZone);
706 707
                }

708
                $dateThen = $timestamp->setTimezone($timeZone);
709 710 711 712 713 714 715

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

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

757 758 759 760

    // number formats


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

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

808
        if ($this->_intlLoaded) {
809
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
810
            return $f->format($value);
David Renty committed
811
        } else {
812 813 814
            if ($decimals === null){
                $decimals = 2;
            }
815
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
816 817 818
        }
    }

819

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

837
        if ($this->_intlLoaded) {
838
            $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
839 840
            return $f->format($value);
        } else {
841 842 843
            if ($decimals === null){
                $decimals = 0;
            }
844
            $value = $value * 100;
845
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
846 847
        }
    }
848 849

    /**
850
     * Formats the value as a scientific number.
851
     *
852 853 854 855
     * @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]].
856
     * @return string the formatted result.
857
     * @throws InvalidParamException if the input value is not numeric.
858
     */
859
    public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
860
    {
David Renty committed
861 862 863
        if ($value === null) {
            return $this->nullDisplay;
        }
864
        $value = $this->normalizeNumericValue($value);
865

866
        if ($this->_intlLoaded){
867
            $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
868 869
            return $f->format($value);
        } else {
870
            if ($decimals !== null) {
871
                return sprintf("%.{$decimals}E", $value);
872 873 874
            } else {
                return sprintf("%.E", $value);
            }
875
        }
David Renty committed
876
    }
877 878

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

        if ($this->_intlLoaded) {
901
            $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
Carsten Brandt committed
902 903 904 905 906 907 908
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    $currency = $formatter->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL);
                } else {
                    $currency = $this->currencyCode;
                }
            }
909
            return $formatter->formatCurrency($value, $currency);
910
        } else {
Carsten Brandt committed
911 912 913 914 915 916
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    throw new InvalidConfigException('The default currency code for the formatter is not defined.');
                }
                $currency = $this->currencyCode;
            }
917
            return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
918 919
        }
    }
920

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

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

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

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

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
996 997 998 999 1000 1001
                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
1002
            }
Carsten Brandt committed
1003 1004
        } else {
            switch ($position) {
1005 1006 1007 1008 1009 1010
                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
1011 1012 1013
            }
        }
    }
David Renty committed
1014

Carsten Brandt committed
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    /**
     * 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);
1037

Carsten Brandt committed
1038 1039
        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1040 1041 1042 1043 1044 1045
                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
1046 1047
            }
        } else {
1048
            switch ($position) {
1049 1050 1051 1052 1053 1054
                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);
1055 1056
            }
        }
Carsten Brandt committed
1057 1058
    }

1059 1060 1061 1062 1063 1064 1065 1066 1067

    /**
     * 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]
1068
     * @throws InvalidParamException if the input value is not numeric.
1069
     */
Carsten Brandt committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    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);
1087

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

        return [$params, $position];
David Renty committed
1110 1111
    }

1112 1113 1114 1115 1116
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1117 1118
    protected function normalizeNumericValue($value)
    {
1119 1120 1121
        if (empty($value)) {
            return 0;
        }
1122 1123 1124 1125 1126 1127 1128 1129 1130
        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;
    }

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

        if ($this->decimalSeparator !== null) {
1149
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1150 1151
        }
        if ($this->thousandSeparator !== null) {
1152
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1153
        }
1154

1155 1156 1157 1158
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1159

Carsten Brandt committed
1160 1161 1162 1163
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1164 1165
            $formatter->setTextAttribute($name, $attribute);
        }
1166 1167 1168 1169 1170 1171
        foreach ($this->numberFormatterOptions as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
1172 1173
        return $formatter;
    }
Qiang Xue committed
1174
}