Formatter.php 49.7 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
     * @param string $value the value to be formatted.
278
     * @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
     * @param string $value the value to be formatted.
291
     * @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
     * @param string $value the value to be formatted.
306
     * @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 string $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
     * @param string $value the value to be formatted.
335
     * @param array $options the tag options in terms of name-value pairs. See [[Html::mailto()]].
336
     * @return string the formatted result.
David Renty committed
337
     */
338
    public function asEmail($value, $options = [])
David Renty committed
339 340 341 342
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
343
        return Html::mailto(Html::encode($value), $value, $options);
David Renty committed
344 345 346 347
    }

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

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

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

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

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


    // date and time formats


David Renty committed
398 399 400
    /**
     * Formats the value as a date.
     * @param integer|string|DateTime $value the value to be formatted. The following
401
     * types of value are supported:
David Renty committed
402 403
     *
     * - an integer representing a UNIX timestamp
404 405 406
     * - 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
407
     *
408 409 410 411 412 413 414 415 416
     * @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.
     *
417
     * @return string the formatted result.
418 419
     * @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
420 421
     * @see dateFormat
     */
422
    public function asDate($value, $format = null)
David Renty committed
423
    {
424 425
        if ($format === null) {
            $format = $this->dateFormat;
426
        }
427
        return $this->formatDateTimeValue($value, $format, 'date');
428
    }
429

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

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

    /**
505 506 507 508 509 510 511 512
     * @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
     *
513
     * @param string $format the format used to convert the value into a date string.
514 515
     * @param string $type 'date', 'time', or 'datetime'.
     * @throws InvalidConfigException if the date format is invalid.
516
     * @return string the formatted result.
517 518 519
     */
    private function formatDateTimeValue($value, $format, $type)
    {
520 521
        $timestamp = $this->normalizeDatetimeValue($value);
        if ($timestamp === null) {
522
            return $this->nullDisplay;
523 524
        }

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

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

600
    /**
601
     * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
602
     * @param integer|string|DateTime $value the value to be formatted. The following
603 604 605
     * types of value are supported:
     *
     * - an integer representing a UNIX timestamp
606 607 608
     * - 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
609 610
     *
     * @return string the formatted result.
611 612 613 614 615 616
     */
    public function asTimestamp($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
617 618
        $timestamp = $this->normalizeDatetimeValue($value);
        return number_format($timestamp->format('U'), 0, '.', '');
619 620 621 622 623
    }

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

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

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

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

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

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

723 724 725 726

    // number formats


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

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

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

785

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

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

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

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

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

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

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

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

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

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

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

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

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

1025 1026 1027 1028 1029 1030 1031 1032 1033

    /**
     * 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]
1034
     * @throws InvalidParamException if the input value is not numeric.
1035
     */
Carsten Brandt committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    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);
1053

Carsten Brandt committed
1054 1055 1056 1057 1058
        // no decimals for bytes
        if ($position === 0) {
            $decimals = 0;
        } elseif ($decimals !== null) {
            $value = round($value, $decimals);
David Renty committed
1059
        }
Carsten Brandt committed
1060 1061 1062
        // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
        $oldThousandSeparator = $this->thousandSeparator;
        $this->thousandSeparator = '';
1063 1064 1065
        if ($this->_intlLoaded) {
            $options[NumberFormatter::GROUPING_USED] = false;
        }
Carsten Brandt committed
1066
        // format the size value
1067 1068 1069 1070 1071 1072
        $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
1073 1074 1075
        $this->thousandSeparator = $oldThousandSeparator;

        return [$params, $position];
David Renty committed
1076 1077
    }

1078 1079 1080 1081 1082
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1083 1084
    protected function normalizeNumericValue($value)
    {
1085 1086 1087
        if (empty($value)) {
            return 0;
        }
1088 1089 1090 1091 1092 1093 1094 1095 1096
        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;
    }

1097 1098
    /**
     * Creates a number formatter based on the given type and format.
1099
     *
Carsten Brandt committed
1100
     * You may overide this method to create a number formatter based on patterns.
1101
     *
Carsten Brandt committed
1102
     * @param integer $style the type of the number formatter.
1103 1104
     * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
     *          ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
Carsten Brandt committed
1105 1106 1107
     * @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]].
1108 1109
     * @return NumberFormatter the created formatter instance
     */
1110
    protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
1111
    {
1112 1113 1114
        $formatter = new NumberFormatter($this->locale, $style);

        if ($this->decimalSeparator !== null) {
1115
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1116 1117
        }
        if ($this->thousandSeparator !== null) {
1118
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1119
        }
1120

1121 1122 1123 1124
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1125

Carsten Brandt committed
1126 1127 1128 1129
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1130 1131
            $formatter->setTextAttribute($name, $attribute);
        }
1132 1133 1134 1135 1136 1137
        foreach ($this->numberFormatterOptions as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
1138 1139
        return $formatter;
    }
Qiang Xue committed
1140
}