Formatter.php 55.3 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

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

Qiang Xue committed
21
/**
22 23
 * Formatter provides a set of commonly used data formatting methods. 
 * 
Qiang Xue committed
24 25 26 27
 * 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.
 *
28
 * Formatter is configured as an application component in [[\yii\base\Application]] by default.
29 30
 * You can access that instance via `Yii::$app->formatter`.
 *
31 32 33
 * 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
34
 * a fallback implementation. Without intl month and day names are in English only.
35 36 37 38 39 40 41
 *
 * @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
42
{
43 44
    /**
     * @var string the text to be displayed when formatting a `null` value.
Carsten Brandt committed
45 46
     * Defaults to `'<span class="not-set">(not set)</span>'`, where `(not set)`
     * will be translated according to [[locale]].
47 48 49 50 51
     */
    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
52
     * Defaults to `['No', 'Yes']`, where `Yes` and `No`
53
     * will be translated according to [[locale]].
54 55
     */
    public $booleanFormat;
David Renty committed
56
    /**
57
     * @var string the locale ID that is used to localize the date and number formatting.
58 59
     * For number and date formatting this is only effective when the
     * [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
60 61 62
     * If not set, [[\yii\base\Application::language]] will be used.
     */
    public $locale;
63
    /**
David Renty committed
64 65 66 67
     * @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
68
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
David Renty committed
69 70 71
     */
    public $timeZone;
    /**
72
     * @var string the default format string to be used to format a [[asDate()|date]].
73
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
74
     *
75
     * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
76 77
     * 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.
David Renty committed
78
     */
79
    public $dateFormat = 'medium';
80
    /**
81
     * @var string the default format string to be used to format a [[asTime()|time]].
82
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
83
     *
84
     * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
85 86
     * 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.
87
     */
88
    public $timeFormat = 'medium';
David Renty committed
89
    /**
90
     * @var string the default format string to be used to format a [[asDateTime()|date and time]].
91
     * This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
92
     *
93
     * It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
94 95 96
     *
     * 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.
David Renty committed
97
     */
98
    public $datetimeFormat = 'medium';
David Renty committed
99 100
    /**
     * @var string the character displayed as the decimal point when formatting a number.
101
     * If not set, the decimal separator corresponding to [[locale]] will be used.
102
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is '.'.
David Renty committed
103 104 105
     */
    public $decimalSeparator;
    /**
106
     * @var string the character displayed as the thousands separator (also called grouping separator) character when formatting a number.
107
     * If not set, the thousand separator corresponding to [[locale]] will be used.
108
     * If [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is ','.
David Renty committed
109 110
     */
    public $thousandSeparator;
111 112 113 114 115 116 117 118 119
    /**
     * @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
120
     * For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:
121 122 123
     *
     * ```php
     * [
Carsten Brandt committed
124 125
     *     NumberFormatter::MIN_FRACTION_DIGITS => 0,
     *     NumberFormatter::MAX_FRACTION_DIGITS => 2,
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
     * ]
     * ```
     */
    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 = [];
148
    /**
149
     * @var string the 3-letter ISO 4217 currency code indicating the default currency to use for [[asCurrency]].
Carsten Brandt committed
150
     * If not set, the currency code corresponding to [[locale]] will be used.
Carsten Brandt committed
151 152
     * 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.
153 154
     */
    public $currencyCode;
David Renty committed
155
    /**
Carsten Brandt committed
156 157
     * @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
158
     */
Carsten Brandt committed
159
    public $sizeFormatBase = 1024;
David Renty committed
160

161
    /**
162
     * @var boolean whether the [PHP intl extension](http://php.net/manual/en/book.intl.php) is loaded.
163 164 165
     */
    private $_intlLoaded = false;

166

167
    /**
168
     * @inheritdoc
David Renty committed
169 170 171 172 173 174
     */
    public function init()
    {
        if ($this->timeZone === null) {
            $this->timeZone = Yii::$app->timeZone;
        }
175 176 177
        if ($this->locale === null) {
            $this->locale = Yii::$app->language;
        }
178
        if ($this->booleanFormat === null) {
179
            $this->booleanFormat = [Yii::t('yii', 'No', [], $this->locale), Yii::t('yii', 'Yes', [], $this->locale)];
David Renty committed
180 181
        }
        if ($this->nullDisplay === null) {
182
            $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)', [], $this->locale) . '</span>';
David Renty committed
183
        }
184
        $this->_intlLoaded = extension_loaded('intl');
185 186 187 188
        if (!$this->_intlLoaded) {
            $this->decimalSeparator = '.';
            $this->thousandSeparator = ',';
        }
David Renty committed
189 190
    }

191
    /**
David Renty committed
192 193 194 195
     * 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.
196
     * @param mixed $value the value to be formatted.
197 198 199
     * @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
200 201 202
     * 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
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
     */
    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 {
221
            throw new InvalidParamException("Unknown format type: $format");
222 223 224 225
        }
    }


226
    // simple formats
227 228


David Renty committed
229 230 231
    /**
     * Formats the value as is without any formatting.
     * This method simply returns back the parameter without any format.
232 233
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
234 235 236 237 238 239 240 241
     */
    public function asRaw($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return $value;
    }
242

David Renty committed
243 244
    /**
     * Formats the value as an HTML-encoded plain text.
245 246
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
247 248 249 250 251 252 253 254
     */
    public function asText($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return Html::encode($value);
    }
255

David Renty committed
256 257
    /**
     * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
258 259
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
260 261 262 263 264 265 266 267 268 269 270 271 272
     */
    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.
273 274
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
275 276 277 278 279 280
     */
    public function asParagraphs($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
281
        return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
David Renty committed
282 283 284 285 286 287
    }

    /**
     * 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.
288
     * @param mixed $value the value to be formatted.
289
     * @param array|null $config the configuration for the HTMLPurifier class.
290
     * @return string the formatted result.
David Renty committed
291 292 293 294 295 296 297 298 299 300 301
     */
    public function asHtml($value, $config = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return HtmlPurifier::process($value, $config);
    }

    /**
     * Formats the value as a mailto link.
302 303
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
304 305 306 307 308 309 310 311 312 313 314
     */
    public function asEmail($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return Html::mailto(Html::encode($value), $value);
    }

    /**
     * Formats the value as an image tag.
315 316
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
317 318 319 320 321 322 323 324 325 326 327
     */
    public function asImage($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return Html::img($value);
    }

    /**
     * Formats the value as a hyperlink.
328 329
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
330 331 332 333 334 335 336
     */
    public function asUrl($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $url = $value;
Carsten Brandt committed
337
        if (strpos($url, '://') === false) {
David Renty committed
338 339
            $url = 'http://' . $url;
        }
340

David Renty committed
341 342 343 344 345
        return Html::a(Html::encode($value), $url);
    }

    /**
     * Formats the value as a boolean.
346 347
     * @param mixed $value the value to be formatted.
     * @return string the formatted result.
David Renty committed
348 349 350 351 352 353 354
     * @see booleanFormat
     */
    public function asBoolean($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
355

David Renty committed
356 357
        return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
    }
358 359 360 361 362


    // date and time formats


David Renty committed
363 364 365
    /**
     * Formats the value as a date.
     * @param integer|string|DateTime $value the value to be formatted. The following
366
     * types of value are supported:
David Renty committed
367 368
     *
     * - an integer representing a UNIX timestamp
369
     * - a string that can be parsed into a UNIX timestamp via `strtotime()`
David Renty committed
370 371
     * - a PHP DateTime object
     *
372 373 374 375 376 377 378 379 380
     * @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.
     *
381 382
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
383
     * @return string the formatted result.
David Renty committed
384 385
     * @see dateFormat
     */
386
    public function asDate($value, $format = null)
David Renty committed
387
    {
388 389
        if ($format === null) {
            $format = $this->dateFormat;
390
        }
391
        return $this->formatDateTimeValue($value, $format, 'date');
392
    }
393

David Renty committed
394 395 396
    /**
     * Formats the value as a time.
     * @param integer|string|DateTime $value the value to be formatted. The following
397
     * types of value are supported:
David Renty committed
398 399
     *
     * - an integer representing a UNIX timestamp
400
     * - a string that can be parsed into a UNIX timestamp via `strtotime()`
David Renty committed
401 402
     * - a PHP DateTime object
     *
403
     * @param string $format the format used to convert the value into a date string.
404 405 406 407 408 409 410 411
     * 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.
     *
412 413
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
414
     * @return string the formatted result.
David Renty committed
415 416
     * @see timeFormat
     */
417
    public function asTime($value, $format = null)
David Renty committed
418
    {
419 420
        if ($format === null) {
            $format = $this->timeFormat;
David Renty committed
421
        }
422 423 424 425 426 427 428 429 430
        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
431
     * - a string that can be parsed into a UNIX timestamp via `strtotime()`
432 433 434 435 436 437 438 439 440 441 442
     * - a PHP DateTime object
     *
     * @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.
     *
443 444
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
     * @throws InvalidConfigException if the date format is invalid.
445
     * @return string the formatted result.
446 447 448 449 450 451
     * @see datetimeFormat
     */
    public function asDatetime($value, $format = null)
    {
        if ($format === null) {
            $format = $this->datetimeFormat;
452
        }
453 454 455
        return $this->formatDateTimeValue($value, $format, 'datetime');
    }

456 457 458
    /**
     * @var array map of short format names to IntlDateFormatter constant values.
     */
459 460 461 462 463 464 465
    private $_dateFormats = [
        'short'  => 3, // IntlDateFormatter::SHORT,
        'medium' => 2, // IntlDateFormatter::MEDIUM,
        'long'   => 1, // IntlDateFormatter::LONG,
        'full'   => 0, // IntlDateFormatter::FULL,
    ];

466 467 468 469 470 471 472
    /**
     * @var array with the standard php definition for short, medium, long an full
     * format as pattern for date, time and datetime.
     * This is used as fallback when the intl extension is not installed.
     */
    private $_phpNameToPattern = [
        'short' => [
473
            'date' => 'n/j/y',
474
            'time' => 'H:i',
475
            'datetime' => 'n/j/y H:i',
476 477 478
        ],
        'medium' => [
            'date' => 'M j, Y',
479 480
            'time' => 'g:i:s A',
            'datetime' => 'M j, Y g:i:s A',
481 482 483 484 485 486 487 488 489 490 491 492 493
        ],
        'long' => [
            'date' => 'F j, Y',
            'time' => 'g:i:sA',
            'datetime' => 'F j, Y g:i:sA',
        ],
        'full' => [
            'date' => 'l, F j, Y',
            'time' => 'g:i:sA T',
            'datetime' => 'l, F j, Y g:i:sA T',
        ],
    ];

494 495 496
    /**
     * @param integer $value normalized datetime value
     * @param string $format the format used to convert the value into a date string.
497 498
     * @param string $type 'date', 'time', or 'datetime'.
     * @throws InvalidConfigException if the date format is invalid.
499
     * @return string the formatted result.
500 501 502 503 504 505
     */
    private function formatDateTimeValue($value, $format, $type)
    {
        $value = $this->normalizeDatetimeValue($value);
        if ($value === null) {
            return $this->nullDisplay;
506 507
        }

508 509 510 511 512 513 514 515 516
        if ($this->_intlLoaded) {
            $format = $this->getIntlDatePattern($format);
            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);
517 518
                }
            } else {
519 520
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
            }
521 522 523 524
            if ($formatter === null) {
                throw new InvalidConfigException(intl_get_error_message());
            }
            return $formatter->format($value);
525 526 527 528
        } else {
            // replace short, medium, long and full with real patterns in case intl is not loaded.
            if (isset($this->_phpNameToPattern[$format][$type])) {
                $format = $this->_phpNameToPattern[$format][$type];
529 530
            } else {
                $format = $this->getPhpDatePattern($format);
531
            }
532 533
            $date = new DateTime(null, new \DateTimeZone($this->timeZone));
            $date->setTimestamp($value);
534 535 536
            return $date->format($format);
        }
    }
537

David Renty committed
538
    /**
539
     * Normalizes the given datetime value as a UNIX timestamp that can be taken by various date/time formatting methods.
Kartik Visweswaran committed
540
     *
541
     * @param mixed $value the datetime value to be normalized.
542
     * @return float the normalized datetime value (int64)
David Renty committed
543
     */
544
    protected function normalizeDatetimeValue($value)
David Renty committed
545
    {
546
        if ($value === null) {
547
            return null;
548
        } elseif (is_string($value)) {
Kartik Visweswaran committed
549 550 551
            if (is_numeric($value) || $value === '') {
                $value = (double)$value;
            } else {
Carsten Brandt committed
552
                $date = new DateTime($value);
Philippe Gaultier committed
553
                $value = (double)$date->format('U');
Kartik Visweswaran committed
554 555
            }
            return $value;
556

Carsten Brandt committed
557
        } elseif ($value instanceof DateTime || $value instanceof DateTimeInterface) {
Philippe Gaultier committed
558
            return (double)$value->format('U');
David Renty committed
559
        } else {
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
            return (double)$value;
        }
    }

    private function getIntlDatePattern($pattern)
    {
        if (strpos($pattern, 'php:') === 0) {
            return $this->convertPatternPhpToIcu(substr($pattern, 4));
        } else {
            return $pattern;
        }
    }

    private function getPhpDatePattern($pattern)
    {
        if (strpos($pattern, 'php:') === 0) {
            return substr($pattern, 4);
        } else {
            return $this->convertPatternIcuToPhp($pattern);
        }
    }

    /**
     * intlFormatter class (ICU based) and DateTime class don't have same format string.
     * These format patterns are completely incompatible and must be converted.
     *
     * This method converts an ICU (php intl) formatted date, time or datetime string in
     * a php compatible format string.
     *
     * @param string $pattern dateformat pattern like 'dd.mm.yyyy' or 'short'/'medium'/
     *          'long'/'full' or 'db
     * @return string with converted date format pattern.
     * @throws InvalidConfigException
     */
    private function convertPatternIcuToPhp($pattern)
    {
        return strtr($pattern, [
            'dd' => 'd',    // day with leading zeros
            'd' => 'j',     // day without leading zeros
            'E' => 'D',     // day written in short form eg. Sun
            'EE' => 'D',
            'EEE' => 'D',
            'EEEE' => 'l',  // day fully written eg. Sunday
            'e' => 'N',     // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
            'ee' => 'N',    // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
            // engl. ordinal st, nd, rd; it's not support by ICU but we added
            'D' => 'z',     // day of the year 0 to 365
            'w' => 'W',     // ISO-8601 week number of year, weeks starting on Monday
            'W' => '',      // week of the current month; isn't supported by php
            'F' => '',      // Day of Week in Month. eg. 2nd Wednesday in July
            'g' => '',      // Modified Julian day. This is different from the conventional Julian day number in two regards.
            'M' => 'n',     // Numeric representation of a month, without leading zeros
            'MM' => 'm',    // Numeric representation of a month, with leading zeros
            'MMM' => 'M',   // A short textual representation of a month, three letters
            'MMMM' => 'F',  // A full textual representation of a month, such as January or March
            'Q' => '',      // number of quarter not supported in php
            'QQ' => '',     // number of quarter '02' not supported in php
            'QQQ' => '',    // quarter 'Q2' not supported in php
            'QQQQ' => '',   // quarter '2nd quarter' not supported in php
            'QQQQQ' => '',  // number of quarter '2' not supported in php
            'Y' => 'Y',     // 4digit year number eg. 2014
            'y' => 'Y',     // 4digit year also
            'yyyy' => 'Y',  // 4digit year also
            'yy' => 'y',    // 2digit year number eg. 14
            'r' => '',      // related Gregorian year, not supported by php
            'G' => '',      // ear designator like AD
            'a' => 'a',     // Lowercase Ante meridiem and Post
            'h' => 'g',     // 12-hour format of an hour without leading zeros 1 to 12h
            'K' => 'g',     // 12-hour format of an hour without leading zeros 0 to 11h, not supported by php
            'H' => 'G',     // 24-hour format of an hour without leading zeros 0 to 23h
            'k' => 'G',     // 24-hour format of an hour without leading zeros 1 to 24h, not supported by php
            'hh' => 'h',    // 12-hour format of an hour with leading zeros, 01 to 12 h
            'KK' => 'h',    // 12-hour format of an hour with leading zeros, 00 to 11 h, not supported by php
            'HH' => 'H',    // 24-hour format of an hour with leading zeros, 00 to 23 h
            'kk' => 'H',    // 24-hour format of an hour with leading zeros, 01 to 24 h, not supported by php
            'm' => 'i',     // Minutes without leading zeros, not supported by php
            'mm' => 'i',    // Minutes with leading zeros
            's' => 's',     // Seconds, without leading zeros, not supported by php
            'ss' => 's',    // Seconds, with leading zeros
            'SSS' => '',    // millisecond (maximum of 3 significant digits), not supported by php
            'A' => '',      // milliseconds in day, not supported by php
            'Z' => 'O',     // Difference to Greenwich time (GMT) in hours
            'ZZ' => 'O',     // Difference to Greenwich time (GMT) in hours
            'ZZZ' => 'O',     // Difference to Greenwich time (GMT) in hours
            'z' => 'T',     // Timezone abbreviation
            'zz' => 'T',     // Timezone abbreviation
            'zzz' => 'T',     // Timezone abbreviation
            'zzzz' => 'T',  // Timzone full name, not supported by php
            'V' => 'e',      // Timezone identifier eg. Europe/Berlin
            'VV' => 'e',
            'VVV' => 'e',
            'VVVV' => 'e'
        ]);
    }

    /**
     * intlFormatter class (ICU based) and DateTime class don't have same format string.
     * These format patterns are completely incompatible and must be converted.
     *
     * This method converts PHP formatted date, time or datetime string in
     * an ICU (php intl) compatible format string.
     *
     * @param string $pattern dateformat pattern like 'd.m.Y' or 'short'/'medium'/
     *          'long'/'full' or 'db
     * @return string with converted date format pattern.
     * @throws InvalidConfigException
     */
    private function convertPatternPhpToIcu($pattern)
    {
        return strtr($pattern, [
            'd' => 'dd',    // day with leading zeros
            'j' => 'd',     // day without leading zeros
            'D' => 'EEE',   // day written in short form eg. Sun
            'l' => 'EEEE',  // day fully written eg. Sunday
            'N' => 'e',     // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
            // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
            'S' => '',      // engl. ordinal st, nd, rd; it's not support by ICU
            'z' => 'D',     // day of the year 0 to 365
            'W' => 'w',     // ISO-8601 week number of year, weeks starting on Monday
            // week of the current month; isn't supported by php
            // Day of Week in Month. eg. 2nd Wednesday in July not supported by php
            // Modified Julian day. This is different from the conventional Julian day number in two regards.
            'n'=> 'M',      // Numeric representation of a month, without leading zeros
            'm' => 'MM',    // Numeric representation of a month, with leading zeros
            'M' => 'MMM',   // A short textual representation of a month, three letters
            'F' => 'MMMM',  // A full textual representation of a month, such as January or March
            // number of quarter not supported in php
            // number of quarter '02' not supported in php
            // quarter 'Q2' not supported in php
            // quarter '2nd quarter' not supported in php
            // number of quarter '2' not supported in php
            'Y' => 'yyyy',  // 4digit year eg. 2014
            'y' => 'yy',    // 2digit year number eg. 14
            // related Gregorian year, not supported by php
            // ear designator like AD
            'a' => 'a',     // Lowercase Ante meridiem and Post am. or pm.
            'A' => 'a',     // Upercase Ante meridiem and Post AM or PM, not supported by ICU
            'g' => 'h',     // 12-hour format of an hour without leading zeros 1 to 12h
            // 12-hour format of an hour without leading zeros 0 to 11h, not supported by php
            'G' => 'H',     // 24-hour format of an hour without leading zeros 0 to 23h
            // 24-hour format of an hour without leading zeros 1 to 24h, not supported by php
            'h' => 'hh',    // 12-hour format of an hour with leading zeros, 01 to 12 h
            // 12-hour format of an hour with leading zeros, 00 to 11 h, not supported by php
            'H' => 'HH',    // 24-hour format of an hour with leading zeros, 00 to 23 h
            // 24-hour format of an hour with leading zeros, 01 to 24 h, not supported by php
            // Minutes without leading zeros, not supported by php
            'i' => 'mm',    // Minutes with leading zeros
            // Seconds, without leading zeros, not supported by php
            's' => 'ss',    // Seconds, with leading zeros
            // millisecond (maximum of 3 significant digits), not supported by php
            // milliseconds in day, not supported by php
            'O' => 'Z',     // Difference to Greenwich time (GMT) in hours
            'T' => 'z',     // Timezone abbreviation
            // Timzone full name, not supported by php
            'e' => 'VV',    // Timezone identifier eg. Europe/Berlin
            'w' => '',      // Numeric representation of the day of the week 0=Sun, 6=Sat, not sup. ICU
            'L' => '',      //Whether it's a leap year 1= leap, 0= normal year, not sup. ICU
            'B' => '',      // Swatch Internet time, 000 to 999, not sup. ICU
            'u' => '',      // Microseconds Note that date() will always generate 000000 since it takes an integer parameter, not sup. ICU
            'P' => '',      // Difference to Greenwich time (GMT) with colon between hours and minutes, not sup. ICU
            'Z' => '',      // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive, not sup. ICU
            'c' => 'yyy-MM-dd\'T\'mm:HH:ssZ', //ISO 8601 date, it works only if nothing else than 'c' is in pattern.
            'r' => 'eee, dd MMM yyyy mm:HH:ss Z', // » RFC 2822 formatted date, it works only if nothing else than 'r' is in pattern
            'U' => ''       // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), not supported in ICU

        ]);
David Renty committed
726 727
    }

728
    /**
729 730 731 732 733 734 735 736 737 738
     * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
     * @param integer|string|DateTime|\DateInterval $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 into a UNIX timestamp via `strtotime()` or that can be passed to a DateInterval constructor.
     * - a PHP DateTime object
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
     *
     * @return string the formatted result.
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
     */
    public function asTimestamp($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return number_format($this->normalizeDatetimeValue($value), 0, '.', '');
    }

    /**
     * Formats the value as the time interval between a date and now in human readable form.
     *
     * @param integer|string|DateTime|\DateInterval $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 into a UNIX timestamp via `strtotime()` or that can be passed to a DateInterval constructor.
     * - a PHP DateTime object
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
     *
759 760
     * @param integer|string|DateTime|\DateInterval $referenceTime if specified the value is used instead of `now`.
     * @return string the formatted result.
761
     * @throws InvalidParamException if the input value can not be evaluated as a date value.
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
     */
    public function asRelativeTime($value, $referenceTime = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        if ($value instanceof \DateInterval) {
            $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 {
                    $interval = new \DateInterval($value);
                } catch (\Exception $e) {
                    // invalid date/time and invalid interval
                    return $this->nullDisplay;
                }
            } else {
                $timezone = new \DateTimeZone($this->timeZone);

                if ($referenceTime === null) {
                    $dateNow = new DateTime('now', $timezone);
                } else {
                    $referenceTime = $this->normalizeDatetimeValue($referenceTime);
                    $dateNow = new DateTime(null, $timezone);
                    $dateNow->setTimestamp($referenceTime);
                }

                $dateThen = new DateTime(null, $timezone);
                $dateThen->setTimestamp($timestamp);

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

        if ($interval->invert) {
            if ($interval->y >= 1) {
803
                return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->locale);
804 805
            }
            if ($interval->m >= 1) {
806
                return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->locale);
807 808
            }
            if ($interval->d >= 1) {
809
                return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->locale);
810 811
            }
            if ($interval->h >= 1) {
812
                return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->locale);
813 814
            }
            if ($interval->i >= 1) {
815
                return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
816 817
            }

818
            return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
819 820
        } else {
            if ($interval->y >= 1) {
821
                return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale);
822 823
            }
            if ($interval->m >= 1) {
824
                return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->locale);
825 826
            }
            if ($interval->d >= 1) {
827
                return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->locale);
828 829
            }
            if ($interval->h >= 1) {
830
                return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->locale);
831 832
            }
            if ($interval->i >= 1) {
833
                return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->locale);
834 835
            }

836
            return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
837 838 839
        }
    }

840 841 842 843

    // number formats


David Renty committed
844
    /**
845 846 847 848 849 850
     * 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.
851
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
852
     */
853
    public function asInteger($value, $options = [], $textOptions = [])
854
    {
David Renty committed
855 856 857
        if ($value === null) {
            return $this->nullDisplay;
        }
858 859
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded) {
860
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
861
            return $f->format($value, NumberFormatter::TYPE_INT64);
David Renty committed
862
        } else {
863
            return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
864 865
        }
    }
866 867

    /**
868 869
     * Formats the value as a decimal number.
     *
870
     * Property [[decimalSeparator]] will be used to represent the decimal point. The
871 872
     * value is rounded automatically to the defined decimal digits.
     *
873
     * @param mixed $value the value to be formatted.
874 875
     * @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`.
876 877 878
     * @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.
879
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
880
     * @see decimalSeparator
881
     * @see thousandSeparator
David Renty committed
882
     */
883
    public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
884 885 886 887
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
888
        $value = $this->normalizeNumericValue($value);
889

890
        if ($this->_intlLoaded) {
891
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
892
            return $f->format($value);
David Renty committed
893
        } else {
894 895 896
            if ($decimals === null){
                $decimals = 2;
            }
897
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
David Renty committed
898 899 900
        }
    }

901

David Renty committed
902
    /**
903
     * Formats the value as a percent number with "%" sign.
904 905 906 907 908
     *
     * @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]].
909
     * @return string the formatted result.
910
     * @throws InvalidParamException if the input value is not numeric.
911
     */
912
    public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
913 914 915 916
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
917
        $value = $this->normalizeNumericValue($value);
918

919
        if ($this->_intlLoaded) {
920
            $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
921 922
            return $f->format($value);
        } else {
923 924 925
            if ($decimals === null){
                $decimals = 0;
            }
926
            $value = $value * 100;
927
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
928 929
        }
    }
930 931

    /**
932
     * Formats the value as a scientific number.
933
     *
934 935 936 937
     * @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]].
938
     * @return string the formatted result.
939
     * @throws InvalidParamException if the input value is not numeric.
940
     */
941
    public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
942
    {
David Renty committed
943 944 945
        if ($value === null) {
            return $this->nullDisplay;
        }
946
        $value = $this->normalizeNumericValue($value);
947

948
        if ($this->_intlLoaded){
949
            $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
950 951
            return $f->format($value);
        } else {
952
            if ($decimals !== null) {
953
                return sprintf("%.{$decimals}E", $value);
954 955 956
            } else {
                return sprintf("%.E", $value);
            }
957
        }
David Renty committed
958
    }
959 960

    /**
961
     * Formats the value as a currency number.
962 963 964 965
     *
     * 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.
     *
966
     * @param mixed $value the value to be formatted.
967
     * @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
Carsten Brandt committed
968
     * If null, [[currencyCode]] will be used.
969 970
     * @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]].
971
     * @return string the formatted result.
972
     * @throws InvalidParamException if the input value is not numeric.
973
     * @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
974
     */
975
    public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
976 977 978 979
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
980
        $value = $this->normalizeNumericValue($value);
981 982

        if ($this->_intlLoaded) {
983
            $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
Carsten Brandt committed
984 985 986 987 988 989 990
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    $currency = $formatter->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL);
                } else {
                    $currency = $this->currencyCode;
                }
            }
991
            return $formatter->formatCurrency($value, $currency);
992
        } else {
Carsten Brandt committed
993 994 995 996 997 998
            if ($currency === null) {
                if ($this->currencyCode === null) {
                    throw new InvalidConfigException('The default currency code for the formatter is not defined.');
                }
                $currency = $this->currencyCode;
            }
999
            return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
1000 1001
        }
    }
1002

1003 1004
    /**
     * Formats the value as a number spellout.
1005 1006 1007
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
1008 1009 1010
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
1011
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
     */
    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 {
1023
            throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
1024 1025
        }
    }
1026

1027 1028
    /**
     * Formats the value as a ordinal value of a number.
1029 1030 1031
     *
     * This function requires the [PHP intl extension](http://php.net/manual/en/book.intl.php) to be installed.
     *
1032 1033 1034
     * @param mixed $value the value to be formatted
     * @return string the formatted result.
     * @throws InvalidParamException if the input value is not numeric.
1035
     * @throws InvalidConfigException when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available.
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
     */
    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 {
1047
            throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
1048 1049
        }
    }
1050

David Renty committed
1051
    /**
Carsten Brandt committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
     * 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]].
1063
     * @return string the formatted result.
1064
     * @throws InvalidParamException if the input value is not numeric.
David Renty committed
1065
     * @see sizeFormat
Carsten Brandt committed
1066
     * @see asSize
David Renty committed
1067
     */
Carsten Brandt committed
1068
    public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
David Renty committed
1069
    {
1070 1071 1072
        if ($value === null) {
            return $this->nullDisplay;
        }
Carsten Brandt committed
1073 1074 1075 1076 1077

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

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1078 1079 1080 1081 1082 1083
                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
1084
            }
Carsten Brandt committed
1085 1086
        } else {
            switch ($position) {
1087 1088 1089 1090 1091 1092
                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
1093 1094 1095
            }
        }
    }
David Renty committed
1096

Carsten Brandt committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    /**
     * 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);
1119

Carsten Brandt committed
1120 1121
        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
1122 1123 1124 1125 1126 1127
                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
1128 1129
            }
        } else {
1130
            switch ($position) {
1131 1132 1133 1134 1135 1136
                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);
1137 1138
            }
        }
Carsten Brandt committed
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    }

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

Carsten Brandt committed
1159 1160 1161 1162 1163
        // no decimals for bytes
        if ($position === 0) {
            $decimals = 0;
        } elseif ($decimals !== null) {
            $value = round($value, $decimals);
David Renty committed
1164
        }
Carsten Brandt committed
1165 1166 1167 1168 1169
        // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
        $oldThousandSeparator = $this->thousandSeparator;
        $this->thousandSeparator = '';
        $options[NumberFormatter::GROUPING_USED] = false;
        // format the size value
1170 1171 1172 1173 1174 1175
        $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
1176 1177 1178
        $this->thousandSeparator = $oldThousandSeparator;

        return [$params, $position];
David Renty committed
1179 1180
    }

1181 1182 1183 1184 1185
    /**
     * @param $value
     * @return float
     * @throws InvalidParamException
     */
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    protected function normalizeNumericValue($value)
    {
        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;
    }

1197 1198
    /**
     * Creates a number formatter based on the given type and format.
1199
     *
Carsten Brandt committed
1200
     * You may overide this method to create a number formatter based on patterns.
1201
     *
Carsten Brandt committed
1202
     * @param integer $style the type of the number formatter.
1203 1204
     * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
     *          ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
Carsten Brandt committed
1205 1206 1207
     * @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]].
1208 1209
     * @return NumberFormatter the created formatter instance
     */
1210
    protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
1211
    {
1212 1213 1214
        $formatter = new NumberFormatter($this->locale, $style);

        if ($this->decimalSeparator !== null) {
1215
            $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
1216 1217
        }
        if ($this->thousandSeparator !== null) {
1218
            $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
1219
        }
1220

1221 1222 1223 1224
        if ($decimals !== null) {
            $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
            $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
        }
1225

Carsten Brandt committed
1226
        foreach ($this->numberFormatterOptions as $name => $value) {
1227 1228
            $formatter->setAttribute($name, $value);
        }
Carsten Brandt committed
1229 1230 1231 1232 1233 1234 1235
        foreach ($options as $name => $value) {
            $formatter->setAttribute($name, $value);
        }
        foreach ($this->numberFormatterTextOptions as $name => $attribute) {
            $formatter->setTextAttribute($name, $attribute);
        }
        foreach ($textOptions as $name => $attribute) {
1236 1237
            $formatter->setTextAttribute($name, $attribute);
        }
1238 1239
        return $formatter;
    }
Qiang Xue committed
1240
}