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

8
namespace yii\i18n;
Erik_r committed
9

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

Qiang Xue committed
24
/**
25 26
 * Formatter provides a set of commonly used data formatting methods.
 *
Qiang Xue committed
27 28 29 30
 * The formatting methods provided by Formatter are all named in the form of `asXyz()`.
 * The behavior of some of them may be configured via the properties of Formatter. For example,
 * by configuring [[dateFormat]], one may control how [[asDate()]] formats the value into a date string.
 *
31
 * Formatter is configured as an application component in [[\yii\base\Application]] by default.
32 33
 * You can access that instance via `Yii::$app->formatter`.
 *
34 35 36
 * The Formatter class is designed to format values according to a [[locale]]. For this feature to work
 * the [PHP intl extension](http://php.net/manual/en/book.intl.php) has to be installed.
 * Most of the methods however work also if the PHP intl extension is not installed by providing
37
 * a fallback implementation. Without intl month and day names are in English only.
38 39 40 41 42 43 44
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Enrica Ruedin <e.ruedin@guggach.com>
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class Formatter extends Component
Qiang Xue committed
45
{
46 47
    /**
     * @var string the text to be displayed when formatting a `null` value.
Carsten Brandt committed
48 49
     * Defaults to `'<span class="not-set">(not set)</span>'`, where `(not set)`
     * will be translated according to [[locale]].
50 51 52 53 54
     */
    public $nullDisplay;
    /**
     * @var array the text to be displayed when formatting a boolean value. The first element corresponds
     * to the text displayed for `false`, the second element for `true`.
Carsten Brandt committed
55
     * Defaults to `['No', 'Yes']`, where `Yes` and `No`
56
     * will be translated according to [[locale]].
57 58
     */
    public $booleanFormat;
David Renty committed
59
    /**
60
     * @var string the locale ID that is used to localize the date and number formatting.
61 62
     * For number and date formatting this is only effective when the
     * [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
63 64 65
     * If not set, [[\yii\base\Application::language]] will be used.
     */
    public $locale;
66
    /**
67 68
     * @var string the time zone to use for formatting time and date values.
     *
David Renty committed
69 70
     * This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
71
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available time zones.
Carsten Brandt committed
72
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
73
     *
74 75
     * Note that the default time zone for input data is assumed to be UTC by default if no time zone is included in the input date value.
     * If you store your data in a different time zone in the database, you have to adjust [[defaultTimeZone]] accordingly.
David Renty committed
76 77
     */
    public $timeZone;
78 79 80 81 82 83 84 85 86
    /**
     * @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.
     */
    public $defaultTimeZone = 'UTC';
David Renty committed
87
    /**
88
     * @var string the default format string to be used to format a [[asDate()|date]].
89
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
90
     *
91
     * 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).
92 93
     * 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.
94 95 96 97 98 99 100
     *
     * For example:
     *
     * ```php
     * 'MM/dd/yyyy' // date in ICU format
     * 'php:m/d/Y' // the same date in PHP format
     * ```
David Renty committed
101
     */
102
    public $dateFormat = 'medium';
103
    /**
104
     * @var string the default format string to be used to format a [[asTime()|time]].
105
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
106
     *
107
     * 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).
108 109
     * 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.
110 111 112 113 114 115 116
     *
     * For example:
     *
     * ```php
     * 'HH:mm:ss' // time in ICU format
     * 'php:H:i:s' // the same time in PHP format
     * ```
117
     */
118
    public $timeFormat = 'medium';
David Renty committed
119
    /**
120
     * @var string the default format string to be used to format a [[asDateTime()|date and time]].
121
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
122
     *
123
     * 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).
124 125 126
     *
     * 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.
127 128 129 130 131 132 133
     *
     * 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
134
     */
135
    public $datetimeFormat = 'medium';
David Renty committed
136 137
    /**
     * @var string the character displayed as the decimal point when formatting a number.
138
     * If not set, the decimal separator corresponding to [[locale]] will be used.
139
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is '.'.
David Renty committed
140 141 142
     */
    public $decimalSeparator;
    /**
143
     * @var string the character displayed as the thousands separator (also called grouping separator) character when formatting a number.
144
     * If not set, the thousand separator corresponding to [[locale]] will be used.
145
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is ','.
David Renty committed
146 147
     */
    public $thousandSeparator;
148 149 150 151 152 153 154 155 156
    /**
     * @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
157
     * For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
158 159 160
     *
     * ```php
     * [
Carsten Brandt committed
161 162
     *     NumberFormatter::MIN_FRACTION_DIGITS => 0,
     *     NumberFormatter::MAX_FRACTION_DIGITS => 2,
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
     * ]
     * ```
     */
    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 = [];
185
    /**
186
     * @var string the 3-letter ISO 4217 currency code indicating the default currency to use for [[asCurrency]].
Carsten Brandt committed
187
     * If not set, the currency code corresponding to [[locale]] will be used.
Carsten Brandt committed
188 189
     * 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.
190 191
     */
    public $currencyCode;
David Renty committed
192
    /**
Carsten Brandt committed
193 194
     * @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
195
     */
Carsten Brandt committed
196
    public $sizeFormatBase = 1024;
David Renty committed
197

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

203

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

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


267
    // simple formats
268 269


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

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

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

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

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

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

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

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

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

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


    // date and time formats


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

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

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

    /**
515 516 517 518 519
     * @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).
520
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
521 522
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
523
     * @param string $format the format used to convert the value into a date string.
524 525
     * @param string $type 'date', 'time', or 'datetime'.
     * @throws InvalidConfigException if the date format is invalid.
526
     * @return string the formatted result.
527 528 529
     */
    private function formatDateTimeValue($value, $format, $type)
    {
530 531
        $timestamp = $this->normalizeDatetimeValue($value);
        if ($timestamp === null) {
532
            return $this->nullDisplay;
533 534
        }

535
        if ($this->_intlLoaded) {
536
            if (strncmp($format, 'php:', 4) === 0) {
537 538
                $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
            }
539 540 541 542 543 544 545
            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);
546 547
                }
            } else {
548 549
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
            }
550 551 552
            if ($formatter === null) {
                throw new InvalidConfigException(intl_get_error_message());
            }
553
            return $formatter->format($timestamp);
554
        } else {
555
            if (strncmp($format, 'php:', 4) === 0) {
556
                $format = substr($format, 4);
557
            } else {
558
                $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
559
            }
560
            if ($this->timeZone != null) {
561
                $timestamp->setTimezone(new DateTimeZone($this->timeZone));
562 563
            }
            return $timestamp->format($format);
564 565
        }
    }
566

David Renty committed
567
    /**
568
     * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
Kartik Visweswaran committed
569
     *
570 571 572 573 574
     * @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).
575
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
576 577
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
     *
578 579
     * @return DateTime the normalized datetime value
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
David Renty committed
580
     */
581
    protected function normalizeDatetimeValue($value)
David Renty committed
582
    {
583
        if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
584
            // skip any processing
Kartik Visweswaran committed
585
            return $value;
586 587 588 589 590
        }
        if (empty($value)) {
            $value = 0;
        }
        try {
591
            if (is_numeric($value)) { // process as unix timestamp, which is always in UTC
592
                if (($timestamp = DateTime::createFromFormat('U', $value, new DateTimeZone('UTC'))) === false) {
593 594 595
                    throw new InvalidParamException("Failed to parse '$value' as a UNIX timestamp.");
                }
                return $timestamp;
596
            } 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)
597
                return $timestamp;
598
            } 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)
599
                return $timestamp;
600
            }
601
            // finally try to create a DateTime object with the value
602
            $timestamp = new DateTime($value, new DateTimeZone($this->defaultTimeZone));
603 604 605 606
            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);
607 608 609
        }
    }

610
    /**
611
     * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
612
     * @param integer|string|DateTime $value the value to be formatted. The following
613 614 615
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
616
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
617
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
618
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
619 620
     *
     * @return string the formatted result.
621 622 623 624 625 626
     */
    public function asTimestamp($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
627 628
        $timestamp = $this->normalizeDatetimeValue($value);
        return number_format($timestamp->format('U'), 0, '.', '');
629 630 631 632 633
    }

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

660
        if ($value instanceof DateInterval) {
661 662 663 664 665 666 667 668
            $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 {
669
                    $interval = new DateInterval($value);
670 671 672 673 674
                } catch (\Exception $e) {
                    // invalid date/time and invalid interval
                    return $this->nullDisplay;
                }
            } else {
675
                $timeZone = new DateTimeZone($this->timeZone);
676 677

                if ($referenceTime === null) {
678
                    $dateNow = new DateTime('now', $timeZone);
679
                } else {
680
                    $dateNow = $this->normalizeDatetimeValue($referenceTime);
681
                    $dateNow->setTimezone($timeZone);
682 683
                }

684
                $dateThen = $timestamp->setTimezone($timeZone);
685 686 687 688 689 690 691

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

        if ($interval->invert) {
            if ($interval->y >= 1) {
692
                return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->locale);
693 694
            }
            if ($interval->m >= 1) {
695
                return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->locale);
696 697
            }
            if ($interval->d >= 1) {
698
                return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->locale);
699 700
            }
            if ($interval->h >= 1) {
701
                return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->locale);
702 703
            }
            if ($interval->i >= 1) {
704
                return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
705
            }
706 707 708
            if ($interval->s == 0) {
                return Yii::t('yii', 'just now', [], $this->locale);
            }
709
            return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
710 711
        } else {
            if ($interval->y >= 1) {
712
                return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale);
713 714
            }
            if ($interval->m >= 1) {
715
                return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->locale);
716 717
            }
            if ($interval->d >= 1) {
718
                return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->locale);
719 720
            }
            if ($interval->h >= 1) {
721
                return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->locale);
722 723
            }
            if ($interval->i >= 1) {
724
                return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->locale);
725
            }
726 727 728
            if ($interval->s == 0) {
                return Yii::t('yii', 'just now', [], $this->locale);
            }
729
            return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
730 731 732
        }
    }

733 734 735 736

    // number formats


David Renty committed
737
    /**
738 739 740 741 742 743
     * 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.
744
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
745
     */
746
    public function asInteger($value, $options = [], $textOptions = [])
747
    {
David Renty committed
748 749 750
        if ($value === null) {
            return $this->nullDisplay;
        }
751 752
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded) {
753
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
754
            $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
755
            return $f->format($value, NumberFormatter::TYPE_INT64);
David Renty committed
756
        } else {
757
            return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
758 759
        }
    }
760 761

    /**
762 763
     * Formats the value as a decimal number.
     *
764
     * Property [[decimalSeparator]] will be used to represent the decimal point. The
765 766
     * value is rounded automatically to the defined decimal digits.
     *
767
     * @param mixed $value the value to be formatted.
768 769
     * @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`.
770 771 772
     * @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.
773
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
774
     * @see decimalSeparator
775
     * @see thousandSeparator
David Renty committed
776
     */
777
    public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
778 779 780 781
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
782
        $value = $this->normalizeNumericValue($value);
783

784
        if ($this->_intlLoaded) {
785
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
786
            return $f->format($value);
David Renty committed
787
        } else {
788 789 790
            if ($decimals === null){
                $decimals = 2;
            }
791
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
792 793 794
        }
    }

795

David Renty committed
796
    /**
797
     * Formats the value as a percent number with "%" sign.
798 799 800 801 802
     *
     * @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]].
803
     * @return string the formatted result.
804
     * @throws InvalidParamException if the input value is not numeric.
805
     */
806
    public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
807 808 809 810
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
811
        $value = $this->normalizeNumericValue($value);
812

813
        if ($this->_intlLoaded) {
814
            $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
815 816
            return $f->format($value);
        } else {
817 818 819
            if ($decimals === null){
                $decimals = 0;
            }
820
            $value = $value * 100;
821
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
822 823
        }
    }
824 825

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

842
        if ($this->_intlLoaded){
843
            $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
844 845
            return $f->format($value);
        } else {
846
            if ($decimals !== null) {
847
                return sprintf("%.{$decimals}E", $value);
848 849 850
            } else {
                return sprintf("%.E", $value);
            }
851
        }
David Renty committed
852
    }
853 854

    /**
855
     * Formats the value as a currency number.
856 857 858 859
     *
     * 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.
     *
860
     * @param mixed $value the value to be formatted.
861
     * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
Carsten Brandt committed
862
     * If null, [[currencyCode]] will be used.
863 864
     * @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]].
865
     * @return string the formatted result.
866
     * @throws InvalidParamException if the input value is not numeric.
867
     * @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
868
     */
869
    public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
870 871 872 873
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
874
        $value = $this->normalizeNumericValue($value);
875 876

        if ($this->_intlLoaded) {
877
            $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
Carsten Brandt committed
878 879 880 881 882 883 884
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    $currency = $formatter->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL);
                } else {
                    $currency = $this->currencyCode;
                }
            }
885
            return $formatter->formatCurrency($value, $currency);
886
        } else {
Carsten Brandt committed
887 888 889 890 891 892
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    throw new InvalidConfigException('The default currency code for the formatter is not defined.');
                }
                $currency = $this->currencyCode;
            }
893
            return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
894 895
        }
    }
896

897 898
    /**
     * Formats the value as a number spellout.
899 900 901
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
902 903 904
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
905
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
906 907 908 909 910 911 912 913 914 915 916
     */
    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 {
917
            throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
918 919
        }
    }
920

921 922
    /**
     * Formats the value as a ordinal value of a number.
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 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 {
941
            throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
942 943
        }
    }
944

David Renty committed
945
    /**
Carsten Brandt committed
946 947 948 949 950 951 952 953 954 955 956
     * 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]].
957
     * @return string the formatted result.
958
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
959
     * @see sizeFormat
Carsten Brandt committed
960
     * @see asSize
David Renty committed
961
     */
Carsten Brandt committed
962
    public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
963
    {
964 965 966
        if ($value === null) {
            return $this->nullDisplay;
        }
Carsten Brandt committed
967 968 969 970 971

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

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
972 973 974 975 976 977
                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
978
            }
Carsten Brandt committed
979 980
        } else {
            switch ($position) {
981 982 983 984 985 986
                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
987 988 989
            }
        }
    }
David Renty committed
990

Carsten Brandt committed
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    /**
     * 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);
1013

Carsten Brandt committed
1014 1015
        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1016 1017 1018 1019 1020 1021
                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
1022 1023
            }
        } else {
1024
            switch ($position) {
1025 1026 1027 1028 1029 1030
                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);
1031 1032
            }
        }
Carsten Brandt committed
1033 1034
    }

1035 1036 1037 1038 1039 1040 1041 1042 1043

    /**
     * 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]
1044
     * @throws InvalidParamException if the input value is not numeric.
1045
     */
Carsten Brandt committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    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);
1063

Carsten Brandt committed
1064 1065 1066 1067 1068
        // no decimals for bytes
        if ($position === 0) {
            $decimals = 0;
        } elseif ($decimals !== null) {
            $value = round($value, $decimals);
David Renty committed
1069
        }
Carsten Brandt committed
1070 1071 1072
        // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
        $oldThousandSeparator = $this->thousandSeparator;
        $this->thousandSeparator = '';
1073 1074 1075
        if ($this->_intlLoaded) {
            $options[NumberFormatter::GROUPING_USED] = false;
        }
Carsten Brandt committed
1076
        // format the size value
1077 1078 1079 1080 1081 1082
        $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
1083 1084 1085
        $this->thousandSeparator = $oldThousandSeparator;

        return [$params, $position];
David Renty committed
1086 1087
    }

1088 1089 1090 1091 1092
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1093 1094
    protected function normalizeNumericValue($value)
    {
1095 1096 1097
        if (empty($value)) {
            return 0;
        }
1098 1099 1100 1101 1102 1103 1104 1105 1106
        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;
    }

1107 1108
    /**
     * Creates a number formatter based on the given type and format.
1109
     *
Alexander Mohorev committed
1110
     * You may override this method to create a number formatter based on patterns.
1111
     *
Carsten Brandt committed
1112
     * @param integer $style the type of the number formatter.
1113 1114
     * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
     *          ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
Carsten Brandt committed
1115 1116 1117
     * @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]].
1118 1119
     * @return NumberFormatter the created formatter instance
     */
1120
    protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
1121
    {
1122 1123 1124
        $formatter = new NumberFormatter($this->locale, $style);

        if ($this->decimalSeparator !== null) {
1125
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1126 1127
        }
        if ($this->thousandSeparator !== null) {
1128
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1129
        }
1130

1131 1132 1133 1134
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1135

Carsten Brandt committed
1136 1137 1138 1139
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1140 1141
            $formatter->setTextAttribute($name, $attribute);
        }
1142 1143 1144 1145 1146 1147
        foreach ($this->numberFormatterOptions as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
1148 1149
        return $formatter;
    }
Qiang Xue committed
1150
}