Formatter.php 48.9 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
    /**
David Renty committed
67 68 69 70
     * @var string the timezone to use for formatting time and date values.
     * This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
Carsten Brandt committed
71
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
72 73 74
     *
     * Note that the input timezone is assumed to be UTC always if no timezone is included in the input date value.
     * Make sure to store datetime values in UTC in your database.
David Renty committed
75 76 77
     */
    public $timeZone;
    /**
78
     * @var string the default format string to be used to format a [[asDate()|date]].
79
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
80
     *
81
     * 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).
82 83
     * 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.
84 85 86 87 88 89 90
     *
     * For example:
     *
     * ```php
     * 'MM/dd/yyyy' // date in ICU format
     * 'php:m/d/Y' // the same date in PHP format
     * ```
David Renty committed
91
     */
92
    public $dateFormat = 'medium';
93
    /**
94
     * @var string the default format string to be used to format a [[asTime()|time]].
95
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
96
     *
97
     * 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).
98 99
     * 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.
100 101 102 103 104 105 106
     *
     * For example:
     *
     * ```php
     * 'HH:mm:ss' // time in ICU format
     * 'php:H:i:s' // the same time in PHP format
     * ```
107
     */
108
    public $timeFormat = 'medium';
David Renty committed
109
    /**
110
     * @var string the default format string to be used to format a [[asDateTime()|date and time]].
111
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
112
     *
113
     * 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).
114 115 116
     *
     * 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.
117 118 119 120 121 122 123
     *
     * 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
124
     */
125
    public $datetimeFormat = 'medium';
David Renty committed
126 127
    /**
     * @var string the character displayed as the decimal point when formatting a number.
128
     * If not set, the decimal separator corresponding to [[locale]] will be used.
129
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is '.'.
David Renty committed
130 131 132
     */
    public $decimalSeparator;
    /**
133
     * @var string the character displayed as the thousands separator (also called grouping separator) character when formatting a number.
134
     * If not set, the thousand separator corresponding to [[locale]] will be used.
135
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is ','.
David Renty committed
136 137
     */
    public $thousandSeparator;
138 139 140 141 142 143 144 145 146
    /**
     * @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
147
     * For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
148 149 150
     *
     * ```php
     * [
Carsten Brandt committed
151 152
     *     NumberFormatter::MIN_FRACTION_DIGITS => 0,
     *     NumberFormatter::MAX_FRACTION_DIGITS => 2,
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
     * ]
     * ```
     */
    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 = [];
175
    /**
176
     * @var string the 3-letter ISO 4217 currency code indicating the default currency to use for [[asCurrency]].
Carsten Brandt committed
177
     * If not set, the currency code corresponding to [[locale]] will be used.
Carsten Brandt committed
178 179
     * 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.
180 181
     */
    public $currencyCode;
David Renty committed
182
    /**
Carsten Brandt committed
183 184
     * @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
185
     */
Carsten Brandt committed
186
    public $sizeFormatBase = 1024;
David Renty committed
187

188
    /**
189
     * @var boolean whether the [PHP intl extension](http://php.net/manual/en/book.intl.php) is loaded.
190 191 192
     */
    private $_intlLoaded = false;

193

194
    /**
195
     * @inheritdoc
David Renty committed
196 197 198 199 200 201
     */
    public function init()
    {
        if ($this->timeZone === null) {
            $this->timeZone = Yii::$app->timeZone;
        }
202 203 204
        if ($this->locale === null) {
            $this->locale = Yii::$app->language;
        }
205
        if ($this->booleanFormat === null) {
206
            $this->booleanFormat = [Yii::t('yii', 'No', [], $this->locale), Yii::t('yii', 'Yes', [], $this->locale)];
David Renty committed
207 208
        }
        if ($this->nullDisplay === null) {
209
            $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)', [], $this->locale) . '</span>';
David Renty committed
210
        }
211
        $this->_intlLoaded = extension_loaded('intl');
212
        if (!$this->_intlLoaded) {
213 214 215 216 217 218
            if ($this->decimalSeparator === null) {
                $this->decimalSeparator = '.';
            }
            if ($this->thousandSeparator === null) {
                $this->thousandSeparator = ',';
            }
219
        }
David Renty committed
220 221
    }

222
    /**
David Renty committed
223 224 225 226
     * 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.
227
     * @param mixed $value the value to be formatted.
228 229 230
     * @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
231 232 233
     * 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
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
     */
    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 {
252
            throw new InvalidParamException("Unknown format type: $format");
253 254 255 256
        }
    }


257
    // simple formats
258 259


David Renty committed
260 261 262
    /**
     * Formats the value as is without any formatting.
     * This method simply returns back the parameter without any format.
263
     * The only exception is a `null` value which will be formatted using [[nullDisplay]].
264 265
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
266 267 268 269 270 271 272 273
     */
    public function asRaw($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return $value;
    }
274

David Renty committed
275 276
    /**
     * Formats the value as an HTML-encoded plain text.
277 278
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
279 280 281 282 283 284 285 286
     */
    public function asText($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return Html::encode($value);
    }
287

David Renty committed
288 289
    /**
     * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
290 291
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
292 293 294 295 296 297 298 299 300 301 302 303 304
     */
    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.
305 306
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
307 308 309 310 311 312
     */
    public function asParagraphs($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
313
        return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
David Renty committed
314 315 316 317 318 319
    }

    /**
     * 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.
320
     * @param mixed $value the value to be formatted.
321
     * @param array|null $config the configuration for the HTMLPurifier class.
322
     * @return string the formatted result.
David Renty committed
323 324 325 326 327 328 329 330 331 332 333
     */
    public function asHtml($value, $config = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return HtmlPurifier::process($value, $config);
    }

    /**
     * Formats the value as a mailto link.
334 335
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
336 337 338 339 340 341 342 343 344 345 346
     */
    public function asEmail($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return Html::mailto(Html::encode($value), $value);
    }

    /**
     * Formats the value as an image tag.
347
     * @param mixed $value the value to be formatted.
348
     * @param string $altText an optional `alt`-tag to be added to the image.
349
     * @return string the formatted result.
David Renty committed
350
     */
351
    public function asImage($value, $altText = '')
David Renty committed
352 353 354 355
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
356
        return Html::img($value, ['alt' => $altText]);
David Renty committed
357 358 359 360
    }

    /**
     * Formats the value as a hyperlink.
361
     * @param mixed $value the value to be formatted.
362
     * @param array $options the tag options in terms of name-value pairs. See [[Html::a()]].
363
     * @return string the formatted result.
David Renty committed
364
     */
365
    public function asUrl($value, $options = [])
David Renty committed
366 367 368 369 370
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $url = $value;
Carsten Brandt committed
371
        if (strpos($url, '://') === false) {
David Renty committed
372 373
            $url = 'http://' . $url;
        }
374

375
        return Html::a(Html::encode($value), $url, $options);
David Renty committed
376 377 378 379
    }

    /**
     * Formats the value as a boolean.
380 381
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
382 383 384 385 386 387 388
     * @see booleanFormat
     */
    public function asBoolean($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
389

David Renty committed
390 391
        return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
    }
392 393 394 395 396


    // date and time formats


David Renty committed
397 398 399
    /**
     * Formats the value as a date.
     * @param integer|string|DateTime $value the value to be formatted. The following
400
     * types of value are supported:
David Renty committed
401 402
     *
     * - an integer representing a UNIX timestamp
403 404 405
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
     *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
David Renty committed
406
     *
407 408 409 410 411 412 413 414 415
     * @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.
     *
416
     * @return string the formatted result.
417 418
     * @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
419 420
     * @see dateFormat
     */
421
    public function asDate($value, $format = null)
David Renty committed
422
    {
423 424
        if ($format === null) {
            $format = $this->dateFormat;
425
        }
426
        return $this->formatDateTimeValue($value, $format, 'date');
427
    }
428

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

493 494 495
    /**
     * @var array map of short format names to IntlDateFormatter constant values.
     */
496 497 498 499 500 501 502 503
    private $_dateFormats = [
        'short'  => 3, // IntlDateFormatter::SHORT,
        'medium' => 2, // IntlDateFormatter::MEDIUM,
        'long'   => 1, // IntlDateFormatter::LONG,
        'full'   => 0, // IntlDateFormatter::FULL,
    ];

    /**
504 505 506 507 508 509 510 511
     * @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).
     *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
512
     * @param string $format the format used to convert the value into a date string.
513 514
     * @param string $type 'date', 'time', or 'datetime'.
     * @throws InvalidConfigException if the date format is invalid.
515
     * @return string the formatted result.
516 517 518
     */
    private function formatDateTimeValue($value, $format, $type)
    {
519 520
        $timestamp = $this->normalizeDatetimeValue($value);
        if ($timestamp === null) {
521
            return $this->nullDisplay;
522 523
        }

524
        if ($this->_intlLoaded) {
525
            if (strncmp($format, 'php:', 4) === 0) {
526 527
                $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
            }
528 529 530 531 532 533 534
            if (isset($this->_dateFormats[$format])) {
                if ($type === 'date') {
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
                } elseif ($type === 'time') {
                    $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
                } else {
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
535 536
                }
            } else {
537 538
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
            }
539 540 541
            if ($formatter === null) {
                throw new InvalidConfigException(intl_get_error_message());
            }
542
            return $formatter->format($timestamp);
543
        } else {
544
            if (strncmp($format, 'php:', 4) === 0) {
545
                $format = substr($format, 4);
546
            } else {
547
                $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
548
            }
549
            if ($this->timeZone != null) {
550
                $timestamp->setTimezone(new DateTimeZone($this->timeZone));
551 552
            }
            return $timestamp->format($format);
553 554
        }
    }
555

David Renty committed
556
    /**
557
     * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
Kartik Visweswaran committed
558
     *
559 560 561 562 563 564 565 566
     * @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).
     *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
567 568
     * @return DateTime the normalized datetime value
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
David Renty committed
569
     */
570
    protected function normalizeDatetimeValue($value)
David Renty committed
571
    {
572
        if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
573
            // skip any processing
Kartik Visweswaran committed
574
            return $value;
575 576 577 578 579
        }
        if (empty($value)) {
            $value = 0;
        }
        try {
580
            if (is_numeric($value)) { // process as unix timestamp
581
                if (($timestamp = DateTime::createFromFormat('U', $value, new DateTimeZone('UTC'))) === false) {
582 583 584
                    throw new InvalidParamException("Failed to parse '$value' as a UNIX timestamp.");
                }
                return $timestamp;
585
            } elseif (($timestamp = DateTime::createFromFormat('Y-m-d', $value, new DateTimeZone('UTC'))) !== false) { // try Y-m-d format (support invalid dates like 2012-13-01)
586
                return $timestamp;
587
            } elseif (($timestamp = DateTime::createFromFormat('Y-m-d H:i:s', $value, new DateTimeZone('UTC'))) !== false) { // try Y-m-d H:i:s format (support invalid dates like 2012-13-01 12:63:12)
588
                return $timestamp;
589
            }
590
            // finally try to create a DateTime object with the value
591
            $timestamp = new DateTime($value, new DateTimeZone('UTC'));
592 593 594 595
            return $timestamp;
        } 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);
596 597 598
        }
    }

599
    /**
600
     * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
601
     * @param integer|string|DateTime $value the value to be formatted. The following
602 603 604
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
605 606 607
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
     *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
608 609
     *
     * @return string the formatted result.
610 611 612 613 614 615
     */
    public function asTimestamp($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
616 617
        $timestamp = $this->normalizeDatetimeValue($value);
        return number_format($timestamp->format('U'), 0, '.', '');
618 619 620 621 622
    }

    /**
     * Formats the value as the time interval between a date and now in human readable form.
     *
623 624 625 626 627 628 629
     * 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
630 631 632
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
633 634 635
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
     *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
636 637
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
     *
638 639
     * @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.
640
     * @return string the formatted result.
641
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
642 643 644 645 646 647 648
     */
    public function asRelativeTime($value, $referenceTime = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

649
        if ($value instanceof DateInterval) {
650 651 652 653 654 655 656 657
            $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 {
658
                    $interval = new DateInterval($value);
659 660 661 662 663
                } catch (\Exception $e) {
                    // invalid date/time and invalid interval
                    return $this->nullDisplay;
                }
            } else {
664
                $timezone = new DateTimeZone($this->timeZone);
665 666 667 668

                if ($referenceTime === null) {
                    $dateNow = new DateTime('now', $timezone);
                } else {
669 670
                    $dateNow = $this->normalizeDatetimeValue($referenceTime);
                    $dateNow->setTimezone($timezone);
671 672
                }

673
                $dateThen = $timestamp->setTimezone($timezone);
674 675 676 677 678 679 680

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

        if ($interval->invert) {
            if ($interval->y >= 1) {
681
                return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->locale);
682 683
            }
            if ($interval->m >= 1) {
684
                return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->locale);
685 686
            }
            if ($interval->d >= 1) {
687
                return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->locale);
688 689
            }
            if ($interval->h >= 1) {
690
                return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->locale);
691 692
            }
            if ($interval->i >= 1) {
693
                return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
694
            }
695 696 697
            if ($interval->s == 0) {
                return Yii::t('yii', 'just now', [], $this->locale);
            }
698
            return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
699 700
        } else {
            if ($interval->y >= 1) {
701
                return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale);
702 703
            }
            if ($interval->m >= 1) {
704
                return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->locale);
705 706
            }
            if ($interval->d >= 1) {
707
                return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->locale);
708 709
            }
            if ($interval->h >= 1) {
710
                return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->locale);
711 712
            }
            if ($interval->i >= 1) {
713
                return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->locale);
714
            }
715 716 717
            if ($interval->s == 0) {
                return Yii::t('yii', 'just now', [], $this->locale);
            }
718
            return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
719 720 721
        }
    }

722 723 724 725

    // number formats


David Renty committed
726
    /**
727 728 729 730 731 732
     * 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.
733
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
734
     */
735
    public function asInteger($value, $options = [], $textOptions = [])
736
    {
David Renty committed
737 738 739
        if ($value === null) {
            return $this->nullDisplay;
        }
740 741
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded) {
742
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
743
            $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
744
            return $f->format($value, NumberFormatter::TYPE_INT64);
David Renty committed
745
        } else {
746
            return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
747 748
        }
    }
749 750

    /**
751 752
     * Formats the value as a decimal number.
     *
753
     * Property [[decimalSeparator]] will be used to represent the decimal point. The
754 755
     * value is rounded automatically to the defined decimal digits.
     *
756
     * @param mixed $value the value to be formatted.
757 758
     * @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`.
759 760 761
     * @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.
762
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
763
     * @see decimalSeparator
764
     * @see thousandSeparator
David Renty committed
765
     */
766
    public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
767 768 769 770
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
771
        $value = $this->normalizeNumericValue($value);
772

773
        if ($this->_intlLoaded) {
774
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
775
            return $f->format($value);
David Renty committed
776
        } else {
777 778 779
            if ($decimals === null){
                $decimals = 2;
            }
780
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
781 782 783
        }
    }

784

David Renty committed
785
    /**
786
     * Formats the value as a percent number with "%" sign.
787 788 789 790 791
     *
     * @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]].
792
     * @return string the formatted result.
793
     * @throws InvalidParamException if the input value is not numeric.
794
     */
795
    public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
796 797 798 799
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
800
        $value = $this->normalizeNumericValue($value);
801

802
        if ($this->_intlLoaded) {
803
            $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
804 805
            return $f->format($value);
        } else {
806 807 808
            if ($decimals === null){
                $decimals = 0;
            }
809
            $value = $value * 100;
810
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
811 812
        }
    }
813 814

    /**
815
     * Formats the value as a scientific number.
816
     *
817 818 819 820
     * @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]].
821
     * @return string the formatted result.
822
     * @throws InvalidParamException if the input value is not numeric.
823
     */
824
    public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
825
    {
David Renty committed
826 827 828
        if ($value === null) {
            return $this->nullDisplay;
        }
829
        $value = $this->normalizeNumericValue($value);
830

831
        if ($this->_intlLoaded){
832
            $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
833 834
            return $f->format($value);
        } else {
835
            if ($decimals !== null) {
836
                return sprintf("%.{$decimals}E", $value);
837 838 839
            } else {
                return sprintf("%.E", $value);
            }
840
        }
David Renty committed
841
    }
842 843

    /**
844
     * Formats the value as a currency number.
845 846 847 848
     *
     * 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.
     *
849
     * @param mixed $value the value to be formatted.
850
     * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
Carsten Brandt committed
851
     * If null, [[currencyCode]] will be used.
852 853
     * @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]].
854
     * @return string the formatted result.
855
     * @throws InvalidParamException if the input value is not numeric.
856
     * @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
857
     */
858
    public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
859 860 861 862
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
863
        $value = $this->normalizeNumericValue($value);
864 865

        if ($this->_intlLoaded) {
866
            $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
Carsten Brandt committed
867 868 869 870 871 872 873
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    $currency = $formatter->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL);
                } else {
                    $currency = $this->currencyCode;
                }
            }
874
            return $formatter->formatCurrency($value, $currency);
875
        } else {
Carsten Brandt committed
876 877 878 879 880 881
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    throw new InvalidConfigException('The default currency code for the formatter is not defined.');
                }
                $currency = $this->currencyCode;
            }
882
            return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
883 884
        }
    }
885

886 887
    /**
     * Formats the value as a number spellout.
888 889 890
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
891 892 893
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
894
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
895 896 897 898 899 900 901 902 903 904 905
     */
    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 {
906
            throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
907 908
        }
    }
909

910 911
    /**
     * Formats the value as a ordinal value of a number.
912 913 914
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
915 916 917
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
918
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
919 920 921 922 923 924 925 926 927 928 929
     */
    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 {
930
            throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
931 932
        }
    }
933

David Renty committed
934
    /**
Carsten Brandt committed
935 936 937 938 939 940 941 942 943 944 945
     * 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]].
946
     * @return string the formatted result.
947
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
948
     * @see sizeFormat
Carsten Brandt committed
949
     * @see asSize
David Renty committed
950
     */
Carsten Brandt committed
951
    public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
952
    {
953 954 955
        if ($value === null) {
            return $this->nullDisplay;
        }
Carsten Brandt committed
956 957 958 959 960

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

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
961 962 963 964 965 966
                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
967
            }
Carsten Brandt committed
968 969
        } else {
            switch ($position) {
970 971 972 973 974 975
                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
976 977 978
            }
        }
    }
David Renty committed
979

Carsten Brandt committed
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    /**
     * 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);
1002

Carsten Brandt committed
1003 1004
        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1005 1006 1007 1008 1009 1010
                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
1011 1012
            }
        } else {
1013
            switch ($position) {
1014 1015 1016 1017 1018 1019
                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);
1020 1021
            }
        }
Carsten Brandt committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    }

    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);
1041

Carsten Brandt committed
1042 1043 1044 1045 1046
        // no decimals for bytes
        if ($position === 0) {
            $decimals = 0;
        } elseif ($decimals !== null) {
            $value = round($value, $decimals);
David Renty committed
1047
        }
Carsten Brandt committed
1048 1049 1050
        // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
        $oldThousandSeparator = $this->thousandSeparator;
        $this->thousandSeparator = '';
1051 1052 1053
        if ($this->_intlLoaded) {
            $options[NumberFormatter::GROUPING_USED] = false;
        }
Carsten Brandt committed
1054
        // format the size value
1055 1056 1057 1058 1059 1060
        $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
1061 1062 1063
        $this->thousandSeparator = $oldThousandSeparator;

        return [$params, $position];
David Renty committed
1064 1065
    }

1066 1067 1068 1069 1070
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1071 1072
    protected function normalizeNumericValue($value)
    {
1073 1074 1075
        if (empty($value)) {
            return 0;
        }
1076 1077 1078 1079 1080 1081 1082 1083 1084
        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;
    }

1085 1086
    /**
     * Creates a number formatter based on the given type and format.
1087
     *
Carsten Brandt committed
1088
     * You may overide this method to create a number formatter based on patterns.
1089
     *
Carsten Brandt committed
1090
     * @param integer $style the type of the number formatter.
1091 1092
     * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
     *          ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
Carsten Brandt committed
1093 1094 1095
     * @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]].
1096 1097
     * @return NumberFormatter the created formatter instance
     */
1098
    protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
1099
    {
1100 1101 1102
        $formatter = new NumberFormatter($this->locale, $style);

        if ($this->decimalSeparator !== null) {
1103
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1104 1105
        }
        if ($this->thousandSeparator !== null) {
1106
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1107
        }
1108

1109 1110 1111 1112
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1113

Carsten Brandt committed
1114 1115 1116 1117
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1118 1119
            $formatter->setTextAttribute($name, $attribute);
        }
1120 1121 1122 1123 1124 1125
        foreach ($this->numberFormatterOptions as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
1126 1127
        return $formatter;
    }
Qiang Xue committed
1128
}