Commit d7b4ea85 by Carsten Brandt

refactored date formatting functions

- removed unformat methods, they do not belong here - removed db format, which is also not purpose of this class - refactored the whole set of methods to be simpler and better maintainable More unit tests needed.
parent 330b8c25
......@@ -4,7 +4,6 @@ Yii Framework 2 Change Log
2.0.0-rc under development
--------------------------
- Enh #2359: Refactored formatter class. One class with or without intl extension and PHP format pattern as standard. (Erik_r)
- Bug #1263: Fixed the issue that Gii and Debug modules might be affected by incompatible asset manager configuration (qiangxue)
- Bug #2314: Gii model generator does not generate correct relation type in some special case (qiangxue)
- Bug #2563: Theming is not working if the path map of the theme contains ".." or "." in the paths (qiangxue)
......@@ -100,6 +99,8 @@ Yii Framework 2 Change Log
- Enh: Added param `hideOnSinglePage` to `yii\widgets\LinkPager` (arturf)
- Enh: Added support for array attributes in `in` validator (creocoder)
- Enh: Improved `yii\helpers\Inflector::slug` to support more cases for Russian, Hebrew and special characters (samdark)
- Chg #2359: Refactored formatter class. One class with or without intl extension and PHP format pattern as standard (Erik_r, cebe)
- `yii\i18n\Formatter` functionality has been merged into `yii\base\Formatter`
- Chg #2898: `yii\console\controllers\AssetController` is now using hashes instead of timestamps (samdark)
- Chg #2913: RBAC `DbManager` is now initialized via migration (samdark)
- Chg #3036: Upgraded Twitter Bootstrap to 3.1.x (qiangxue)
......
......@@ -13,11 +13,8 @@ use IntlDateFormatter;
use NumberFormatter;
use yii\helpers\HtmlPurifier;
use yii\helpers\Html;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\i18n\FormatDefs;
/**
* Formatter provides a set of commonly used data formatting methods.
*
......@@ -28,20 +25,8 @@ use yii\i18n\FormatDefs;
* Formatter is configured as an application component in [[\yii\base\Application]] by default.
* You can access that instance via `Yii::$app->formatter`.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*
* Refactoring of formatter class by
* @author Enrica Ruedin <e.ruedin@guggach.com>
*
* Original version of Yii2 has two formatter classes in "yii\base\formatter" and "yii\i18n\formatter". Fist uses PHP
* to handle date formats with php format patterns like "Y-m-d" -> "2014-06-02" while second uses icu format
* patterns from php extension "intl" like "yyyy-mm-dd" -> "2014-06-02". Further icu knows terms like "short", "medium",
* "long" and "full" which holds predefined patterns which are missing in yii\base formatter.
*
* I have seen an extension which uses yii::$app->formatter->format($value, ['date', 'Y-m-d']). This will crash
* if a developper uses yii\i18n formatter because intl doesn't know this format pattern.
*
* TODO docs
* This refactored formatter version combines localized i18n with base functions. If "intl" extension is installed
* ICU standard is used internally. If "intl" want to be used or can't be loaded most functionality is simulated with php.
* A separate definiton class in 'yii\i18n\FormatDefs.php' has an array with localized format defintions.
......@@ -55,24 +40,35 @@ use yii\i18n\FormatDefs;
* All number fomatters of yii\i18n\ are merged with yii\base in this formatter. Formatted numbers aren't readable for
* a machine as numeric. Therefore an "unformat" function for all "format" types has been built.
*
* Databases need the iso format for date, time and datetime normally. (eg. 2014-06-02 14:53:02) The dbFormat can be
* configured in the component section also.
*
* For currency amounts the currency code is taken from "intl" (if loaded). Otherwise it can be defined in a localizing
* array (formatterIntl). The rounding rule can be defined in config with "$roundingIncrement". For Swiss Francs formatter rounds
* automatically to 5 cents.
*
* */
class Formatter extends yii\base\Component
* @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
{
/**
* @var string the text to be displayed when formatting a `null` value.
* Defaults to `'<span class="not-set">(not set)</span>'`.
*/
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`.
* Defaults to `['No', 'Yes']`.
*/
public $booleanFormat;
/**
* @var string the locale ID that is used to localize the date and number formatting.
* If not set, [[\yii\base\Application::language]] will be used.
*/
public $locale;
/**
/**
* @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`.
......@@ -81,38 +77,53 @@ class Formatter extends yii\base\Component
*/
public $timeZone;
/**
* @var string the default format string to be used to format a date using PHP date() function.
* Possible values are: "short", "medium", "long", "full" as predifined date formats like in ICU or
* format pattern in php format. NOT ICU format!
*
* After initialization of object the named predifined format will be replaced by the corresponding
* php format string.
*/
public $dateFormat = 'medium'; // php:'Y-m-d';
/**
* @var string the default format string to be used to format a time using PHP date() function.
* see "$dateFormat"
*/
public $timeFormat = 'medium'; // php: 'H:i:s';
/**
* @var string the default format string to be used to format a date and time using PHP date() function.
* see "$dateFormat"
* @var string the default format string to be used to format a date.
* 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).
*/
public $datetimeFormat = 'medium'; // php: 'Y-m-d H:i:s';
public $dateFormat = 'medium';
/**
*
* @var string default format pattern for database requested format.
* @var string the default format string to be used to format a time.
* 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).
*/
public $dbFormat = ['date' => 'Y-m-d','time' => 'H:i:s', 'dbtimeshort'=>'H:i' ,'datetime' => 'Y-m-d H:i:s', 'dbdatetimeshort' => 'Y-m-d H:i'];
public $timeFormat = 'medium';
/**
* @var string the text to be displayed when formatting a null. Defaults to '<span class="not-set">(not set)</span>'.
* @var string the default format string to be used to format a date and time.
* 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).
*/
public $nullDisplay;
public $datetimeFormat = 'medium';
/**
* @var array the text to be displayed when formatting a boolean value. The first element corresponds
* to the text display for false, the second element for true. Defaults to `['No', 'Yes']`.
* @var array with the standard php definition for short, medium, long an full
* format as pattern for date, time and datetime.
* The number behind pattern is the array index of localized formatterIntl array
* for same combination like [short][date][1] = 2
*/
public $booleanFormat;
private $_phpNameToPattern = [ // TODO make this configureable?
'short' => [
'date' => 'd.m.Y',
'time' => 'H:i',
'datetime' => 'y-m-d H:i',
],
'medium' => [
'date' => 'M j, Y',
'time' => 'H:i:s',
'datetime' => 'Y-m-d H:i:s',
],
'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',
],
];
// TODO refactor number formatters
/**
* @var array the options to be set for the NumberFormatter objects (eg. grouping used). Please refer to
* [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
......@@ -131,25 +142,23 @@ class Formatter extends yii\base\Component
public $numberTextFormartOptions = [];
/**
* @var string the character displayed as the decimal point when formatting a number.
* If not set, "." will be used.
* If not set, the decimal separator corresponding to [[locale]] will be used.
* If PHP `intl` extension is not available, the default value is '.'.
*/
public $decimalSeparator;
/**
* @var string the character displayed as the thousands separator character when formatting a number.
* If not set, "," will be used.
* If not set, the thousand separator corresponding to [[locale]] will be used.
* If PHP `intl` extension is not available, the default value is ','.
*/
public $thousandSeparator;
/**
*
* @var string: Standard currency code for currency formatting. With "intl" library not usefull
* because "intl" uses the local currency code by default. There with "intl" it should null.
* Without "intl" the currency code can be defined in array in position 14 per locale code.
* With this var a standard code can be defined in config file.
* @var string the international currency code displayed when formatting a number.
* If not set, the currency code corresponding to [[locale]] will be used.
*/
public $currencyCode;
/**
*
* @var type float "intl" numberformat library knows a rounding increment
* @var float "intl" numberformat library knows a rounding increment
* This means that any value is rounded to this increment.
* Example: increment of 0.05 rounds values <= 2.024 to 2.00 / values >= 2.025 to 2.05
*/
......@@ -166,70 +175,16 @@ class Formatter extends yii\base\Component
'decimalSeparator' => null,
];
/**
* @var boolean shows if the php extension is loaded
* If intl is loaded the icu format and intDateFormatter is used
*/
private $_intlLoaded = false;
/**
* @var private strings hold the format patterns for date, time and
* dattime in ICU format. ICU format is used internally only.
*
* @var boolean whether the php `intl` extension is loaded.
*/
private $_dateFormatIcu;
private $_timeFormatIcu;
private $_datetimeFormatIcu;
// IntlDateFormatter can't be used here because there will be an error
// if intl extension isn't loaded.
private $_dateFormatsIcu = [
'short' => 3, // IntlDateFormatter::SHORT,
'medium' => 2, // IntlDateFormatter::MEDIUM,
'long' => 1, // IntlDateFormatter::LONG,
'full' => 0, // IntlDateFormatter::FULL,
];
private $_intlLoaded = false;
/**
*
* @var type array with the standard php definition for short, medium, long an full
* format as pattern for date, time and datetime.
* The number behind pattern is the array index of localized formatterIntl array
* for same combination like [short][date][1] = 2
*/
private $_PhpNameToPattern = [
'short' => [
'date' => ['y-m-d', 2],
'time' => ['H:i', 6],
'datetime' => ['y-m-d H:i', 10],
],
'medium' => [
'date' => ['Y-m-d', 3],
'time' => ['H:i:s', 7],
'datetime' => ['Y-m-d H:i:s', 11]
],
'long' => [
'date' => ['F j, Y', 4],
'time' => ['g:i:sA', 8],
'datetime' => ['F j, Y g:i:sA', 12]
],
'full' => [
'date' => ['l, F j, Y', 5],
'time' => ['g:i:sA T', 9],
'datetime' => ['l, F j, Y g:i:sA T', 13]
],
];
/**
*
* @var type arry: stores the originally configured values for dateFormat,
* timeFormat and datetimeFormat, because the variables values will be replaced
* by the format pattern during initialization.
*/
private $_originalConfig = [];
/**
* Initializes the component.
* @inheritdoc
*/
public function init()
{
......@@ -241,36 +196,27 @@ class Formatter extends yii\base\Component
$this->locale = Yii::$app->language;
}
if (empty($this->booleanFormat)) {
if ($this->booleanFormat === null) {
$this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')];
}
if ($this->nullDisplay === null) {
$this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)') . '</span>';
}
if (extension_loaded('intl')) {
$this->_intlLoaded = true;
$this->numberFormatOptions= [NumberFormatter::ROUNDING_MODE => NumberFormatter::ROUND_HALFUP];
}
$this->_originalConfig['date'] = $this->dateFormat;
$this->setFormatPattern($this->dateFormat, 'date');
$this->_originalConfig['time'] = $this->timeFormat;
$this->setFormatPattern($this->timeFormat, 'time');
$this->_originalConfig['datetime'] = $this->datetimeFormat;
$this->setFormatPattern($this->datetimeFormat, 'datetime');
$this->setDecimalSeparator($this->decimalSeparator);
$this->setThousandSeparator($this->thousandSeparator);
if (preg_match('/\bde-CH\b|\bfr-CH\b|\bit-CH\b/', $this->locale)){
// Swiss currency amounts must be rounded to 0.05 (5-Rappen) instead of
// 0.01 as usual
$this->roundingIncrCurrency = '0.05';
}
$this->_intlLoaded = extension_loaded('intl');
// TODO refactor number formatters
// if (extension_loaded('intl')) {
// $this->_intlLoaded = true;
// $this->numberFormatOptions = [NumberFormatter::ROUNDING_MODE => NumberFormatter::ROUND_HALFUP];
// }
//
// if (preg_match('/\bde-CH\b|\bfr-CH\b|\bit-CH\b/', $this->locale)){
// // Swiss currency amounts must be rounded to 0.05 (5-Rappen) instead of
// // 0.01 as usual
// $this->roundingIncrCurrency = '0.05';
// }
}
/**
......@@ -304,943 +250,616 @@ class Formatter extends yii\base\Component
if ($this->hasMethod($method)) {
return call_user_func_array([$this, $method], $params);
} else {
throw new InvalidParamException("Unknown type: $format");
throw new InvalidParamException("Unknown format type: $format");
}
}
// simple formats
/**
* Unformats a formatted value based on the given format type to a machine readable value.
*
* This method will call one of the "as" methods available in this class to do the formatting.
* For type "xyz", the method "ufXyz" will be used. For example, if the format is "double",
* then [[ufDouble()]] will be used. Format names are case insensitive.
* @param mixed $value the value to be unformatted
* @param string|array $format the format of the value, e.g., "double", "currency". To specify additional
* parameters of the unformatting 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
* method. For example, a format of `['date', 'Y-m-d', 'php']` will cause the invocation of `ufDate($value, 'Y-m-d', 'php')`.
* For more details see ufXXX functions.
* @return string the formatting result
* @throws InvalidParamException if the type is not supported by this class.
* Formats the value as is without any formatting.
* This method simply returns back the parameter without any format.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function unformat($value, $format)
public function asRaw($value)
{
if (is_array($format)) {
if (!isset($format[0])) {
throw new InvalidParamException('The $format array must contain at least one element.');
if ($value === null) {
return $this->nullDisplay;
}
$f = $format[0];
$format[0] = $value;
$params = $format;
$format = $f;
} else {
$params = [$value];
return $value;
}
$method = 'uf' . $format;
if ($this->hasMethod($method)) {
return call_user_func_array([$this, $method], $params);
} else {
throw new InvalidParamException("Unknown type: $format");
/**
* Formats the value as an HTML-encoded plain text.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asText($value)
{
if ($value === null) {
return $this->nullDisplay;
}
return Html::encode($value);
}
/**
* 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 type string $pattern: dateformat pattern like 'dd.mm.yyyy' or 'short'/'medium'/
* 'long'/'full' or 'db
* @param type string $type: if pattern has a name like 'short', type must define if
* a date, time or datetime string should be formatted.
* @return type string with converted date format pattern.
* @throws InvalidConfigException
* Formats the value as an HTML-encoded plain text with newlines converted into breaks.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function convertPatternIcuToPhp($pattern, $type = 'date') {
if (preg_match('/\bshort\b|\bmedium\b|\blong\b|\bfull\b/', strtolower($pattern))){
if ($this->_intlLoaded){
switch (strtolower($type)){
case 'date':
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormatsIcu[$pattern], IntlDateFormatter::NONE, $this->timeZone);
break;
case 'time':
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormatsIcu[$pattern], $this->timeZone);
break;
case 'datetime':
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormatsIcu[$pattern], $this->_dateFormatsIcu[$pattern], $this->timeZone);
break;
default:
throw new InvalidConfigException('Conversion of ICU to PHP with a not supported type [date, time, datetime].');
}
$pattern = $formatter->getPattern();
public function asNtext($value)
{
if ($value === null) {
return $this->nullDisplay;
}
else {
// throw new InvalidConfigException('ICU pattern "short", "medium", "long" and "full" can\'t be used if intl extension isn\'t loaded.');
$localArr = FormatDefs::definition($this->locale);
if (isset($localArr[0])){
return $localArr[$this->_PhpNameToPattern[$pattern][$type][1]];
} else {
return $this->_PhpNameToPattern[strtolower($pattern)][$type][0];
// _PhpNameToPattern['short']['date'] --> 'y-m-d'
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.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asParagraphs($value)
{
if ($value === null) {
return $this->nullDisplay;
}
} elseif (strtolower($pattern) === 'db'){
return $this->dbFormat[strtolower($type)];
return str_replace('<p></p>', '', '<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
}
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'
]);
/**
* 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.
* @param mixed $value the value to be formatted
* @param array|null $config the configuration for the HTMLPurifier class.
* @return string the formatted result
*/
public function asHtml($value, $config = null)
{
if ($value === null) {
return $this->nullDisplay;
}
return HtmlPurifier::process($value, $config);
}
/**
* 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 type string $pattern: dateformat pattern like 'd.m.Y' or 'short'/'medium'/
* 'long'/'full' or 'db
* @param type string $type: if pattern has a name like 'short', type must define if
* a date, time or datetime string should be formatted.
* @return type string with converted date format pattern.
* @throws InvalidConfigException
* Formats the value as a mailto link.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function convertPatternPhpToIcu($pattern, $type = 'date'){
if (preg_match('/\bshort\b|\bmedium\b|\blong\b|\bfull\b/', strtolower($pattern))){
$type = strtolower($type);
if ($this->_intlLoaded){
switch ($type){
case 'date':
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormatsIcu[$pattern], IntlDateFormatter::NONE, $this->timeZone);
break;
case 'time':
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormatsIcu[$pattern], $this->timeZone);
break;
case 'datetime':
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormatsIcu[$pattern], $this->_dateFormatsIcu[$pattern], $this->timeZone);
break;
default:
throw new InvalidConfigException('Conversion of ICU with a not supported type [date, time, datetime].');
public function asEmail($value)
{
if ($value === null) {
return $this->nullDisplay;
}
return $formatter->getPattern();
}
else {
$localArr = FormatDefs::definition($this->locale);
if (isset($localArr[0])){
return $localArr[$this->_PhpNameToPattern[$pattern][$type][1]];
} else {
return $this->_PhpNameToPattern[strtolower($pattern)][$type][0];
// _PhpNameToPattern['short']['date'] --> 'y-m-d'
}
}
} elseif ($pattern === 'db'){
return $this->convertPatternIcuToPhp($this->dbFormat[strtolower($type)], $type);
}
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
'T' => '', // Number of days in the given month eg. 28 through 31, not sup. ICU
'L' => '', //Whether it's a leap year 1= leap, 0= normal year, not sup. ICU
'O' => '', // ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. 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
]);
}
/**
* Returns the fully locale string like 'en-US' or 'de-CH'
* @return type string
*/
public function getLocale(){
return $this->locale;
}
/**
* Set a new local different to Yii configuration for temporale reason.
* @param string $locale language code and country code.
* @return Formatter object
*/
public function setLocale($locale = 'en-US'){
$this->locale = $locale;
// Reset dateformat pattern as requested by yii formatter config
$this->setFormatPattern($this->_originalConfig['date'], 'date');
$this->setFormatPattern($this->_originalConfig['time'], 'time');
$this->setFormatPattern($this->_originalConfig['datetime'], 'datetime');
$this->setDecimalSeparator();
$this->setThousandSeparator();
return $this;
}
/**
*
* @param string $searchFor: delivers pattern for "date", "time" and "datetime"
* @param string $patternFor: "php" or "icu" format convention. PHP is standard.
* @return string: returns a string with format pattern requested by input parameter
* @throws \yii\base\InvalidParamException if invalid input parameters.
*/
public function getFormatPattern($formatFor = 'date', $patternFor = 'php') {
$formatFor = strtolower($formatFor);
$patternFor = strtolower($patternFor);
if ($patternFor === 'php' or $patternFor === 'icu'){
switch ($formatFor) {
case 'date':
return $patternFor === 'php' ? $this->dateFormat : $this->_dateFormatIcu;
break;
case 'time':
return $patternFor === 'php' ? $this->timeFormat : $this->_timeFormatIcu;
break;
case 'datetime':
return $patternFor === 'php' ? $this->datetimeFormat : $this->_datetimeFormatIcu;
break;
default:
throw new \yii\base\InvalidParamException('Parameter "formatFor" is \''. $formatFor . '\'. Valid is date, time or datetime.');
}
} else {
throw new \yii\base\InvalidParamException('Paramter "patternFor" is \'' .$patternFor. '\'. Valid is "php" or "icu".');
}
}
/**
* Sets a new date or time or datetime format and converts it from php to icu or versa.
* @param string $format: Formatting pattern like 'd-m-Y' (php) or 'dd-mm-yyyy' icu.
* @param string $formatFor: Specifies which target is newly formated. Option are: date, time or datetime.
* @param string $patternFor: Specifies which pattern standard is use. PHP is standard.
* @return Formatter object for chaining.
* @throws \yii\base\InvalidParamException
*/
public function setFormatPattern($format, $formatFor, $patternFor = 'php'){
$formatFor = strtolower($formatFor);
$patternFor = strtolower($patternFor);
if (preg_match('/\bdate\b|\btime\b|\bdatetime\b/', $formatFor) != true){
throw new \yii\base\InvalidParamException('Invalid parameter for "formatFor": "$formatFor". Allowed values are: date, time, datetime.');
}
if (preg_match('/\bshort\b|\bmedium\b|\blong\b|\bfull\b/', strtolower($format))) {
$format = strtolower($format);
if ($this->_intlLoaded) {
switch ($formatFor) {
case 'date':
$this->dateFormat = $this->convertPatternIcuToPhp($format, 'date');
$this->_dateFormatIcu = $this->convertPatternPhpToIcu($this->dateFormat);
break;
case 'time':
$this->timeFormat = $this->convertPatternIcuToPhp($format, 'time');
$this->_timeFormatIcu = $this->convertPatternPhpToIcu($this->timeFormat);
break;
case 'datetime':
$this->datetimeFormat = $this->convertPatternIcuToPhp($format, 'datetime');
$this->_datetimeFormatIcu = $this->convertPatternPhpToIcu($this->datetimeFormat);
break;
}
} else {
$localArr = FormatDefs::definition($this->locale);
if (isset($localArr[0])){
switch ($formatFor){
case 'date':
$this->dateFormat = $localArr[$this->_PhpNameToPattern[$format][$formatFor][1]];
$this->_dateFormatIcu = $this->convertPatternPhpToIcu($this->dateFormat);
break;
case 'time':
$this->timeFormat = $localArr[$this->_PhpNameToPattern[$format][$formatFor][1]];
$this->_timeFormatIcu = $this->convertPatternPhpToIcu($this->timeFormat);
break;
case 'datetime':
$this->datetimeFormat = $localArr[$this->_PhpNameToPattern[$format][$formatFor][1]];
$this->_datetimeFormatIcu = $this->convertPatternPhpToIcu($this->datetimeFormat);
break;
}
} else {
// _PhpNameToPattern['short']['date'] --> 'y-m-d'
switch ($formatFor){
case 'date':
$this->dateFormat = $this->_PhpNameToPattern[$format][$formatFor][0];
$this->_dateFormatIcu = $this->convertPatternPhpToIcu($this->dateFormat);
break;
case 'time':
$this->timeFormat = $this->_PhpNameToPattern[$format][$formatFor][0];
$this->_timeFormatIcu = $this->convertPatternPhpToIcu($this->timeFormat);
break;
case 'datetime':
$this->datetimeFormat = $this->_PhpNameToPattern[$format][$formatFor][0];
$this->_datetimeFormatIcu = $this->convertPatternPhpToIcu($this->datetimeFormat);
break;
}
}
}
} else {
if ($patternFor === 'php') {
switch ($formatFor){
case 'date':
$this->dateFormat = $format;
$this->_dateFormatIcu = $this->convertPatternPhpToIcu($format, $formatFor);
break;
case 'time':
$this->timeFormat = $format;
$this->_timeFormatIcu = $this->convertPatternPhpToIcu($format, $formatFor);
break;
case 'datetime':
$this->datetimeFormat = $format;
$this->_datetimeFormatIcu = $this->convertPatternPhpToIcu($format, $formatFor);
break;
}
} elseif ($patternFor === 'icu') {
switch ($formatFor){
case 'date':
$this->dateFormat = $this->convertPatternIcuToPhp($format, $formatFor);
$this->_dateFormatIcu = $format;
break;
case 'time':
$this->timeFormat = $this->convertPatternIcuToPhp($format, $formatFor);
$this->_timeFormatIcu = $format;
break;
case 'datetime':
$this->datetimeFormat = $this->convertPatternIcuToPhp($format, $formatFor);
$this->_datetimeFormatIcu = $format;
break;
}
}
}
return $this;
}
/**
* Sets the decimal separator to a defined string. If string is null the localized
* standard (icu) will be taken. Without loaded "intl" extension the definition can be
* adapted in FormatDefs.php.
* @param string $sign: one sign which is set.
* @return Formatter object
*/
public function setDecimalSeparator($sign = null){
if ($sign === null){
if ($this->_intlLoaded){
$formatter = new NumberFormatter($this->locale, NumberFormatter::DECIMAL);
$this->decimalSeparator = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
} else {
$localArr = FormatDefs::definition($this->locale);
if (isset($localArr[0])){
$this->decimalSeparator = $localArr[0];
} else {
$this->decimalSeparator = '.';
}
}
} else {
$this->decimalSeparator = $sign;
}
return $this;
}
public function getDecimalSeparator(){
return $this->decimalSeparator;
}
/**
* Sets the thousand separator to a defined string. If string is null the localized
* standard (icu) will be taken. Without loaded "intl" extension the definition can be
* adapted in FormatDefs.php.
* @param string $sign: one sign which is set.
* @return Formatter object
*/
public function setThousandSeparator($sign = null){
if ($sign === null){
if ($this->_intlLoaded){
$formatter = new NumberFormatter($this->locale, NumberFormatter::DECIMAL);
$this->thousandSeparator = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
} else {
$localArr = FormatDefs::definition($this->locale);
if (isset($localArr[0])){
$this->thousandSeparator = $localArr[1];
} else {
$this->thousandSeparator = ',';
}
}
} else {
$this->thousandSeparator = $sign;
}
return $this;
}
public function getThousandSeparator(){
return $this->thousandSeparator;
}
/**
* Formats the value as is without any formatting.
* This method simply returns back the parameter without any format.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asRaw($value)
{
if ($value === null) {
return $this->nullDisplay;
}
return $value;
}
public function ufRaw($value){
if ($value === $this->nullDisplay);
return null;
return Html::mailto(Html::encode($value), $value);
}
/**
* Formats the value as an HTML-encoded plain text.
* Formats the value as an image tag.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asText($value)
public function asImage($value)
{
if ($value === null) {
return $this->nullDisplay;
}
return Html::encode($value);
}
public function ufText($value){
if ($value === Html::encode($this->nullDisplay)){
return null;
}
return Html::img($value);
}
/**
* Formats the value as an HTML-encoded plain text with newlines converted into breaks.
* Formats the value as a hyperlink.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asNtext($value)
public function asUrl($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.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asParagraphs($value)
{
if ($value === null) {
return $this->nullDisplay;
$url = $value;
if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
$url = 'http://' . $url;
}
return str_replace('<p></p>', '', '<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
return Html::a(Html::encode($value), $url);
}
/**
* 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.
* Formats the value as a boolean.
* @param mixed $value the value to be formatted
* @param array|null $config the configuration for the HTMLPurifier class.
* @return string the formatted result
* @see booleanFormat
*/
public function asHtml($value, $config = null)
public function asBoolean($value)
{
if ($value === null) {
return $this->nullDisplay;
}
return HtmlPurifier::process($value, $config);
}
/**
* Formats the value as a mailto link.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asEmail($value)
{
if ($value === null) {
return $this->nullDisplay;
return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
}
return Html::mailto(Html::encode($value), $value);
}
/**
* Formats the value as an image tag.
* @param mixed $value the value to be formatted
* @return string the formatted result
*/
public function asImage($value)
{
if ($value === null) {
return $this->nullDisplay;
}
// date and time formats
return Html::img($value);
}
/**
* Formats the value as a hyperlink.
* @param mixed $value the value to be formatted
* Formats the value as a date.
* @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 into a UNIX timestamp via `strtotime()` TODO
* - 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.
*
* @throws InvalidParamException
* @throws InvalidConfigException
* @return string the formatted result
* @see dateFormat
*/
public function asUrl($value)
public function asDate($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
$url = $value;
if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
$url = 'http://' . $url;
if ($format === null) {
$format = $this->dateFormat;
}
return Html::a(Html::encode($value), $url);
return $this->formatDateTimeValue($value, $format, 'date');
}
/**
* Formats the value as a boolean.
* @param mixed $value the value to be formatted
* Formats the value as a time.
* @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 into a UNIX timestamp via `strtotime()` TODO
* - a PHP DateTime object
*
* @param string $format the format used to convert the value into a date string.
* 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.
*
* @throws InvalidParamException
* @throws InvalidConfigException
* @return string the formatted result
* @see booleanFormat
* @see timeFormat
*/
public function asBoolean($value)
public function asTime($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
}
public function ufBoolean($value){
if (Yii::t('yii', 'No')){
return false;
} elseif (Yii::t('yii', 'Yes')){
return true;
} else {
throw new InvalidParamException('Value :' . $value . ' isn\'t a boolean yes or no value.');
if ($format === null) {
$format = $this->timeFormat;
}
return $this->formatDateTimeValue($value, $format, 'time');
}
/**
* Formats the value as a date.
* 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
* - a string that can be parsed into a UNIX timestamp via `strtotime()`
* - a string that can be parsed into a UNIX timestamp via `strtotime()` TODO
* - a PHP DateTime object
*
* @param string $targetFormat (optional): the format pattern used to convert the value into a date string.
* 'short', 'medium', 'long', 'full' or pattern like 'j-n-Y'
* @param string $inputFormat (optional): the format pattern of $value if it isn't a ISO or local date string.
* @param string $formatType (optional): Specifies the targetFormat and inputFormat pattern. Value 'php' or 'icu'
* @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.
*
* @throws InvalidParamException
* @throws InvalidConfigException
* @return string the formatted result
* @see dateFormat
* @see datetimeFormat
*/
public function asDate($value, $targetFormat = 'date', $inputFormat = null, $formatType = 'php')
public function asDatetime($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
if ($format === null) {
$format = $this->datetimeFormat;
}
$formatType = strtolower($formatType);
if ($formatType != 'php' and $formatType != 'icu'){
throw new InvalidParamException('"' . $formatType . '" is not a valid value, only "php" and "icu".');
return $this->formatDateTimeValue($value, $format, 'datetime');
}
$value = $this->normalizeDatetimeValue($value, $inputFormat);
if ($value === null){
return null;
private $_dateFormats = [
'short' => 3, // IntlDateFormatter::SHORT,
'medium' => 2, // IntlDateFormatter::MEDIUM,
'long' => 1, // IntlDateFormatter::LONG,
'full' => 0, // IntlDateFormatter::FULL,
];
/**
* @param integer $value normalized datetime value
* @param string $format the format used to convert the value into a date string.
* @param $type
* @throws InvalidConfigException
* @return string the formatted result
*/
private function formatDateTimeValue($value, $format, $type)
{
$value = $this->normalizeDatetimeValue($value);
if ($value === null) {
return $this->nullDisplay;
}
if ($this->_intlLoaded){
if ($targetFormat === 'date') {
$targetFormat = $this->_dateFormatIcu;
} elseif ($targetFormat === 'db'){
$targetFormat = $this->convertPatternPhpToIcu($this->dbFormat['date']);
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 {
if ($formatType === 'php'){
$targetFormat = $this->convertPatternPhpToIcu($targetFormat, 'date');
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
}
}
if (isset($this->_dateFormatsIcu[$targetFormat])) {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$targetFormat], IntlDateFormatter::NONE, $this->timeZone);
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($targetFormat);
}
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}else {
if ($targetFormat === 'date') {
$targetFormat = $this->dateFormat;
} else {
if ($formatType === 'php'){
if (isset($this->_dateFormatsIcu[$targetFormat])){ // names like "short", "medium" etc. in $format
$format = $this->convertPatternIcuToPhp($targetFormat, 'date');
// 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];
}
} else { // icu format
$format = $this->convertPatternIcuToPhp($targetFormat, 'date');
}
}
$date = new DateTime('@'.$value);
$format = $this->getPhpDatePattern($format);
$date = new DateTime(null, new \DateTimeZone($this->timeZone));
$date->setTimestamp($value);
return $date->format($format);
}
}
public function ufDate($value, $targetFormat = 'db', $inputFormat = null, $formatType = 'php'){
if ($targetFormat === 'db'){
return asDate($value, 'db', $inputFormat, $formatType);
} elseif ($targetFormat === 'timestamp'){
return asTimestamp($value, $inputFormat, $formatType);
} else {
throw new InvalidParamException('targetFormat must be "db" or "timestamp". Your value is ' . $value );
/**
* Formats a date, time or datetime in a float number as timestamp (seconds since 01-01-1970).
* @param string $value
* @return float timestamp
*/
public function asTimestamp($value)
{
if ($value === null) {
return $this->nullDisplay;
}
return number_format($this->normalizeDatetimeValue($value), 0, '.', '');
}
/**
* Formats the value as a time.
* @param integer|string|DateTime $value the value to be formatted. The following
* 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()`
* - 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)
*
* @param string $format the format used to convert the value into a date string.
* If null, [[timeFormat]] will be used. The format string should be one
* that can be recognized by the PHP `date()` function.
* @param integer|string|DateTime|\DateInterval $referenceTime if specified the value is used instead of now
* @return string the formatted result
* @see timeFormat
*/
public function asTime($value, $targetFormat = 'time', $inputFormat = null, $formatType = 'php')
public function asRelativeTime($value, $referenceTime = null)
{
if ($value === null) {
return $this->nullDisplay;
}
$formatType = strtolower($formatType);
if ($formatType != 'php' and $formatType != 'icu'){
throw new InvalidParamException('"' . $formatType . '" is not a valid value, only "php" and "icu".');
}
$value = $this->normalizeDatetimeValue($value, $inputFormat);
if ($value === null){
return null;
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 ($this->_intlLoaded){
if ($targetFormat === 'time') {
$targetFormat = $this->_timeFormatIcu;
} elseif ($targetFormat === 'db'){
$targetFormat = $this->convertPatternPhpToIcu($this->dbFormat['time']);
if ($referenceTime === null) {
$dateNow = new DateTime('now', $timezone);
} else {
if ($formatType === 'php'){
$targetFormat = $this->convertPatternPhpToIcu($targetFormat, 'time');
$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 (isset($this->_dateFormatsIcu[$targetFormat])) {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$targetFormat], $this->timeZone);
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($targetFormat);
}
if ($interval->invert) {
if ($interval->y >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y]);
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
if ($interval->m >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m]);
}
return $formatter->format($value);
}else {
if ($targetFormat === 'time') {
$targetFormat = $this->timeFormat;
if ($interval->d >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d]);
}
if ($interval->h >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h]);
}
if ($interval->i >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i]);
}
return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s]);
} else {
if ($formatType === 'php'){
if (isset($this->_dateFormatsIcu[$targetFormat])){ // names like "short", "medium" etc. in $format
$format = $this->convertPatternIcuToPhp($targetFormat, 'time');
if ($interval->y >= 1) {
return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y]);
}
} else { // icu format
$format = $this->convertPatternIcuToPhp($targetFormat, 'time');
if ($interval->m >= 1) {
return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m]);
}
if ($interval->d >= 1) {
return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d]);
}
if ($interval->h >= 1) {
return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h]);
}
$date = new DateTime('@'.$value);
return $date->format($format);
if ($interval->i >= 1) {
return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i]);
}
}
public function ufTime($value, $targetFormat = 'db', $inputFormat = null, $formatType = 'php'){
if ($targetFormat === 'db'){
return asTime($value, 'db', $inputFormat, $formatType);
} elseif ($targetFormat === 'timestamp'){
return asTimestamp($value, $inputFormat, $formatType);
} else {
throw new InvalidParamException('targetFormat must be "db" or "timestamp". Your value is ' . $value );
return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s]);
}
}
/**
* 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
* - a string that can be parsed into a UNIX timestamp via `strtotime()`
* - a PHP DateTime object
* Normalizes the given datetime value as one that can be taken by various date/time formatting methods.
*
* @param string $format the format used to convert the value into a date string.
* If null, [[datetimeFormat]] will be used. The format string should be one
* that can be recognized by the PHP `date()` function.
* @return string the formatted result
* @see datetimeFormat
* @param mixed $value the datetime value to be normalized.
* @return float the normalized datetime value (int64)
*/
public function asDatetime($value, $targetFormat = 'datetime', $inputFormat = null, $formatType = 'php')
protected function normalizeDatetimeValue($value)
{
if ($value === null) {
return $this->nullDisplay;
}
$formatType = strtolower($formatType);
if ($formatType != 'php' and $formatType != 'icu'){
throw new InvalidParamException('"' . $formatType . '" is not a valid value, only "php" and "icu".');
}
return null;
} elseif (is_string($value)) {
if (is_numeric($value) || $value === '') {
$value = (double)$value;
} else {
try {
$date = new DateTime($value);
/** $date = new DateTime($value); ==> constructor crashes with
* an invalid date in $value (eg. 2014-06-35) and can't be
* catched by php because is fatal error.
* Consequence was to find another solution which doesn't crash
*/
// TODO docs state strtotime()
// foreach($FormatPatterns as $format){
// $date = DateTime::createFromFormat($format, $value);
// if ( !($date === false)) break;
// }
$value = $this->normalizeDatetimeValue($value, $inputFormat);
if ($value === null){
} catch (\Exception $e) {
return null;
}
if ($this->_intlLoaded){
if ($targetFormat === 'datetime') {
$targetFormat = $this->_datetimeFormatIcu;
} elseif ($targetFormat === 'db'){
$targetFormat = $this->convertPatternPhpToIcu($this->dbFormat['datetime']);
} else {
if ($formatType === 'php'){
$targetFormat = $this->convertPatternPhpToIcu($targetFormat, 'datetime');
if ($date === false){
return null;
}
$value = (double)$date->format('U');
}
if (isset($this->_dateFormatsIcu[$targetFormat])) {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$targetFormat], $this->_dateFormats[$targetFormat], $this->timeZone);
return $value;
} elseif ($value instanceof DateTime || $value instanceof \DateTimeInterface) {
return (double)$value->format('U');
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($targetFormat);
}
return (double)$value;
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}else {
if ($targetFormat === 'datetime') {
$targetFormat = $this->datetimeFormat;
private function getIntlDatePattern($pattern)
{
if (strpos($pattern, 'php:') === 0) {
return $this->convertPatternPhpToIcu(substr($pattern, 4));
} else {
if ($formatType === 'php'){
if (isset($this->_dateFormatsIcu[$targetFormat])){ // names like "short", "medium" etc. in $format
$format = $this->convertPatternIcuToPhp($targetFormat, 'datetime');
}
} else { // icu format
$format = $this->convertPatternIcuToPhp($targetFormat, 'datetime');
}
}
$date = new DateTime('@'.$value);
return $date->format($format);
return $pattern;
}
}
public function ufDatetime($value, $targetFormat = 'db', $inputFormat = null, $formatType = 'php'){
if ($targetFormat === 'db'){
return asDatetime($value, 'db', $inputFormat, $formatType);
} elseif ($targetFormat === 'timestamp'){
return asTimestamp($value, $inputFormat, $formatType);
private function getPhpDatePattern($pattern)
{
if (strpos($pattern, 'php:') === 0) {
return substr($pattern, 4);
} else {
throw new InvalidParamException('targetFormat must be "db" or "timestamp". Your value is ' . $value );
return $this->convertPatternIcuToPhp($pattern);
}
}
/**
* Formats a date, time or datetime in a float number as timestamp (seconds since 01-01-1970).
* @param string $value Date in dbFormat or local format or individual format (see inputFormat)
* @param string $inputFormat if the date format in value is individual the format pattern must be given here.
* @return float with timestamp
* 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
*/
public function asTimestamp($value, $inputFormat = null){
return $this->normalizeDatetimeValue($value, $inputFormat);
private function convertPatternIcuToPhp($pattern)
{
if (isset($this->_dateFormats[$pattern])) {
return $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'
]);
}
/**
* Normalizes the given datetime value as one that can be taken by various date/time formatting methods.
* intlFormatter class (ICU based) and DateTime class don't have same format string.
* These format patterns are completely incompatible and must be converted.
*
* @param mixed $value the datetime value to be normalized.
* @param string $inputPattern format of $value if not database format or local format.
* @return float the normalized datetime value (int64)
* 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
*/
protected function normalizeDatetimeValue($value, $inputPattern = null, $patternFor = 'php')
private function convertPatternPhpToIcu($pattern)
{
if ($value === null){
return null;
if (isset($this->_dateFormats[$pattern])) {
return $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
'T' => '', // Number of days in the given month eg. 28 through 31, not sup. ICU
'L' => '', //Whether it's a leap year 1= leap, 0= normal year, not sup. ICU
'O' => '', // ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. 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
if ($inputPattern != null){
if (strtolower($patternFor) === 'icu'){
$FormatPatterns['individual'] = $this->convertPatternIcuToPhp($inputPattern);
} elseif (strtolower($patternFor) === 'php') {
$FormatPatterns['individual'] = $inputPattern;
} else{
throw new InvalidParamException('patternFor must be "php" or "icu" only. Your value is ' . $patternFor );
}
} else {
$FormatPatterns = $this->dbFormat;
$FormatPatterns['locDate'] = $this->dateFormat;
$FormatPatterns['locTime'] = $this->timeFormat;
$FormatPatterns['locDatetime'] = $this->datetimeFormat;
]);
}
if (is_string($value)) {
if (is_numeric($value) || $value === '') {
$value = (double)$value;
} else {
try {
/** $date = new DateTime($value); ==> constructor crashes with
* an invalid date in $value (eg. 2014-06-35) and can't be
* catched by php because is fatal error.
* Consequence was to find another solution which doesn't crash
*/
foreach($FormatPatterns as $format){
$date = DateTime::createFromFormat($format, $value);
if ( !($date === false)) break;
}
// number formats
} catch (Exception $e) {
return null;
}
if ($date === false){
return null;
}
$value = (double)$date->format('U');
}
return $value;
// TODO refactor number formatters
} elseif ($value instanceof DateTime || $value instanceof \DateTimeInterface) {
return (double)$value->format('U');
} else {
return (double)$value;
}
}
/**
* Formats the value as an integer and rounds decimals with math rule
......@@ -1270,12 +889,32 @@ class Formatter extends yii\base\Component
}
}
public function ufInteger($value){
if ($value === null) {
return null;
/**
* Formats the value as a number with decimal and thousand separators.
* This method is a synomym for asDouble.
* @param mixed $value the value to be formatted
* @param integer $decimals the number of digits after the decimal point
* @return string the formatted result
* @see decimalSeparator
* @see thousandSeparator
*/
public function asNumber($value, $decimals = 0, $roundIncr = null, $grouping = true)
{
return $this->asDouble($value, $decimals, $roundIncr, $grouping);
}
$value = $this->unformatNumber($value, 'int');
return round($value , 0);
/**
* Formats the value as a decimal number. This method is a synonym for asDouble
* @see method asDouble
* @param mixed $value the value to be formatted
* @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* for details on how to specify a format.
* @return string the formatted result.
*/
public function asDecimal($value, $decimals = null, $roundIncr = null, $grouping = true)
{
return $this->asDouble($value, $decimals, $roundIncr, $grouping);
}
/**
......@@ -1368,58 +1007,18 @@ class Formatter extends yii\base\Component
}
}
public function ufDouble($value){
if ($value === null){
return null;
}
return $this->unformatNumber($value);
}
/**
* Formats the value as a number with decimal and thousand separators.
* This method is a synomym for asDouble.
* @param mixed $value the value to be formatted
* @param integer $decimals the number of digits after the decimal point
* @return string the formatted result
* @see decimalSeparator
* @see thousandSeparator
*/
public function asNumber($value, $decimals = 0, $roundIncr = null, $grouping = true)
{
return $this->asDouble($value, $decimals, $roundIncr, $grouping);
}
public function ufNumber($value){
return $this->ufDouble($value);
}
/**
* Formats the value as a decimal number. This method is a synonym for asDouble
* @see method asDouble
* @param mixed $value the value to be formatted
* @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* for details on how to specify a format.
* @return string the formatted result.
*/
public function asDecimal($value, $decimals = null, $roundIncr = null, $grouping = true)
{
return $this->asDouble($value, $decimals, $roundIncr, $grouping);
}
public function ufDecimal($value){
return $this->ufDouble($value);
}
/**
* Formats the value as a percent number with "%" sign.
* @param mixed $value the value to be formatted. It must be a factor eg. 0.75 -> 75%
* @param string $decimals Number of decimals (default = 2) or format pattern ICU
* @param string $format Number of decimals (default = 2) or format pattern ICU
* Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* for details on how to specify a format.
* @return string the formatted result.
*/
public function asPercent($value, $decimals = 0, $grouping = true)
public function asPercent($value, $format = null, $decimals = 0, $grouping = true)
{
$format = null;
if(is_numeric($decimals)){
$decimals = intval($decimals); // number of digits after decimal
} else {
......@@ -1456,12 +1055,6 @@ class Formatter extends yii\base\Component
}
}
public function ufPercent($value){
if ($value === null){
return null;
}
return $this->unformatNumber($value) / 100;
}
/**
* Formats the value as a scientific number.
......@@ -1502,91 +1095,56 @@ class Formatter extends yii\base\Component
}
}
public function ufScientific($value){
if ($value === null){
return null;
}
$value = $value + 0;
if (is_float($value)){
return $value;
} else {
throw new InvalidParamException('Parameter value must be a scientific value, not ' . $value);
}
}
/**
* Formats the value as a currency number.
* @param mixed $value the value to be formatted
* @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.
* @param float $roundIncr: Amount to which smaller fractation are rounded. Ex. 0.05 -> <=2.024 to 2.00 / >=2.025 to 2.05
* works with "intl" library only.
* @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* for details on how to specify a format.
* for details on how to specify a format. TODO ignored when not intl
* @param float $roundIncrement : Amount to which smaller fractation are rounded. Ex. 0.05 -> <=2.024 to 2.00 / >=2.025 to 2.05
* works with "intl" library only.
* @param null $grouping
* @throws InvalidParamException
* @return string the formatted result.
*/
public function asCurrency($value, $currency = null, $roundIncr = null, $grouping = true)
public function asCurrency($value, $currency = null, $format = null, $roundIncrement = null, $grouping = null)
{
$format = null;
if ($value === null) {
return $this->nullDisplay;
}
if (is_string($value)){
if (is_numeric($value)){
if (is_string($value)) {
if (is_numeric($value)) {
$value = (float)$value;
} else {
throw new InvalidParamException('"' . $value . '" is not a numeric value.');
}
}
if ($currency === null and $this->currencyCode != null){
if ($currency === null) {
$currency = $this->currencyCode;
}
if ($roundIncr === null and $this->roundingIncrCurrency != null){
$roundIncr = $this->roundingIncrCurrency;
if ($roundIncrement === null and $this->roundingIncrCurrency != null){
$roundIncrement = $this->roundingIncrCurrency;
}
// if (true == false){
if ($this->_intlLoaded) {
if (trim($currency) === '' and $currency !== null){
$f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $format);
} else {
$f = $this->createNumberFormatter(NumberFormatter::CURRENCY, $format);
}
if ($grouping === false){
$f->setAttribute(NumberFormatter::GROUPING_USED, false);
}
if ($roundIncr !== null){
$f->setAttribute(NumberFormatter::ROUNDING_INCREMENT, $roundIncr);
$formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, $format);
if ($grouping !== null){
$formatter->setAttribute(NumberFormatter::GROUPING_USED, false);
}
if ($currency === null){
return $f->format($value);
} else {
return $f->formatCurrency($value, $currency);
if ($roundIncrement !== null){
$formatter->setAttribute(NumberFormatter::ROUNDING_INCREMENT, $roundIncrement);
}
return $formatter->formatCurrency($value, $currency);
} else {
$localArr = FormatDefs::definition($this->locale);
if ($currency === null){
if (isset($localArr[14])){
$currency = $localArr[14]; // 14 = currency code
} else {
$currency = 'USD';
return $currency . ' ' . $this->asDouble($value, 2, $roundIncrement, $grouping);
}
}
$value = $currency . ' ' . $this->asDouble($value, 2, $roundIncr, $grouping);
$t = 'test';
return $value;
}
}
public function ufCurrency($value){
if ($value === null){
return null;
}
return $this->unformatNumber($value);
}
/**
* Formats the value in bytes as a size in human readable form.
......@@ -1628,127 +1186,8 @@ class Formatter extends yii\base\Component
return $verbose ? Yii::t('yii', '{n, plural, =1{# petabyte} other{# petabytes}}', $params) : Yii::t('yii', '{n} PB', $params);
}
}
public function ufSize($value){
$messures = ['b', 'kb', 'mb', 'gb' , 'tb', 'pb' ,'bytes', 'kilobytes' , 'megabytes', 'gigabytes', 'terabytes', 'petabytes',
'byte', 'kilobyte' , 'megabyte', 'gigabyte', 'terabyte', 'petabyte',
'o', 'ko', 'mo', 'go', 'to', 'po', 'octet', 'kilooctet', 'megaoctet', 'gigaoctet' , 'teraoctet', 'petaoctet',
'octets', 'kilooctets', 'megaoctets', 'gigaoctets' , 'teraoctets', 'petaoctets'];
if ($value === null){
return null;
}
$found = false;
$ufValue = $this->unformatNumber($value);
foreach ($messures as $key => $search) {
if (preg_match('/\b'.$search.'\b/i', $value)) {
$found = true;
break;
}
}
if ($found === true){
$pos = $key % 6;
while ($pos > 0) { // kb or more
$ufValue = $ufValue * $this->sizeFormat['base'];
$pos--;
}
} else {
throw new InvalidParamException('Parameter value isn\'t memory size formatted string like Mb.' );
}
return $ufValue;
}
/**
* 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)
*
* @param integer|string|DateTime|\DateInterval $referenceTime if specified the value is used instead of now
* @return string the formatted result
*/
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) {
return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y]);
}
if ($interval->m >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m]);
}
if ($interval->d >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d]);
}
if ($interval->h >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h]);
}
if ($interval->i >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i]);
}
return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s]);
} else {
if ($interval->y >= 1) {
return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y]);
}
if ($interval->m >= 1) {
return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m]);
}
if ($interval->d >= 1) {
return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d]);
}
if ($interval->h >= 1) {
return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h]);
}
if ($interval->i >= 1) {
return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i]);
}
return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s]);
}
}
/**
* Creates a number formatter based on the given type and format.
* @param integer $type the type of the number formatter
......@@ -1782,29 +1221,4 @@ class Formatter extends yii\base\Component
return $formatter;
}
/**
* Removes formatting information for a "numeric" string and sets a "."
* as decimalseparator.
* @param string $value formatted number/currency like "EUR 13.250,53"
* @return float of unformatted machine readable number like "13250.53"
*/
protected function unformatNumber($value, $numberType = 'dec'){
if ($value === null) {
return null;
}
$cleanString = preg_replace('/([^0-9\.,])/i', '', $value);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $value);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
if ($numberType != 'dec'){ // integer only
$stringWithCommaOrDot = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
}
return (float) str_replace(',', '.', $stringWithCommaOrDot);
}
}
......@@ -4,6 +4,20 @@
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
// override information about intl
use yiiunit\framework\base\FormatterTest;
function extension_loaded($name)
{
if ($name === 'intl' && FormatterTest::$enableIntl !== null) {
return FormatterTest::$enableIntl;
}
return \extension_loaded($name);
}
namespace yiiunit\framework\base;
use yii\base\Formatter;
......@@ -16,6 +30,8 @@ use DateInterval;
*/
class FormatterTest extends TestCase
{
public static $enableIntl;
/**
* @var Formatter
*/
......@@ -24,8 +40,23 @@ class FormatterTest extends TestCase
protected function setUp()
{
parent::setUp();
$this->mockApplication();
$this->formatter = new Formatter();
// emulate disabled intl extension
// enable it only for tests prefixed with testIntl
static::$enableIntl = null;
if (strncmp($this->getName(false), 'testIntl', 8) === 0) {
if (!extension_loaded('intl')) {
$this->markTestSkipped('intl extension is not installed.');
}
static::$enableIntl = true;
} else {
static::$enableIntl = false;
}
$this->mockApplication([
'timeZone' => 'UTC'
]);
$this->formatter = new Formatter(['locale' => 'en-US']);
}
protected function tearDown()
......@@ -34,6 +65,28 @@ class FormatterTest extends TestCase
$this->formatter = null;
}
public function testFormat()
{
$value = time();
$this->assertSame(date('M j, Y', $value), $this->formatter->format($value, 'date'));
$this->assertSame(date('M j, Y', $value), $this->formatter->format($value, 'DATE'));
$this->assertSame(date('Y/m/d', $value), $this->formatter->format($value, ['date', 'Y/m/d']));
$this->setExpectedException('\yii\base\InvalidParamException');
$this->assertSame(date('Y-m-d', $value), $this->formatter->format($value, 'data'));
}
// public function testSetLocale(){
// $value = '12300';
// $this->formatter->setLocale('de-DE');
// $this->assertSame('12.300,00', $this->formatter->asDouble($value, 2));
// $value = time();
// $this->assertSame(date('d.m.Y', $value), $this->formatter->asDate($value));
// $this->formatter->setLocale('en-US');
//
// }
public function testAsRaw()
{
$value = '123';
......@@ -42,6 +95,8 @@ class FormatterTest extends TestCase
$this->assertSame($value, $this->formatter->asRaw($value));
$value = '<>';
$this->assertSame($value, $this->formatter->asRaw($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asRaw(null));
}
......@@ -53,6 +108,8 @@ class FormatterTest extends TestCase
$this->assertSame("$value", $this->formatter->asText($value));
$value = '<>';
$this->assertSame('&lt;&gt;', $this->formatter->asText($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asText(null));
}
......@@ -66,6 +123,8 @@ class FormatterTest extends TestCase
$this->assertSame('&lt;&gt;', $this->formatter->asNtext($value));
$value = "123\n456";
$this->assertSame("123<br />\n456", $this->formatter->asNtext($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asNtext(null));
}
......@@ -83,6 +142,8 @@ class FormatterTest extends TestCase
$this->assertSame("<p>123</p>\n<p>456</p>", $this->formatter->asParagraphs($value));
$value = "123\n\n\n456";
$this->assertSame("<p>123</p>\n<p>456</p>", $this->formatter->asParagraphs($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asParagraphs(null));
}
......@@ -95,13 +156,32 @@ class FormatterTest extends TestCase
{
$value = 'test@sample.com';
$this->assertSame("<a href=\"mailto:$value\">$value</a>", $this->formatter->asEmail($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asEmail(null));
}
public function testAsUrl()
{
$value = 'http://www.yiiframework.com/';
$this->assertSame("<a href=\"$value\">$value</a>", $this->formatter->asUrl($value));
$value = 'https://www.yiiframework.com/';
$this->assertSame("<a href=\"$value\">$value</a>", $this->formatter->asUrl($value));
$value = 'www.yiiframework.com/';
$this->assertSame("<a href=\"http://$value\">$value</a>", $this->formatter->asUrl($value));
$value = 'https://www.yiiframework.com/?name=test&value=5"';
$this->assertSame("<a href=\"https://www.yiiframework.com/?name=test&amp;value=5&quot;\">https://www.yiiframework.com/?name=test&amp;value=5&quot;</a>", $this->formatter->asUrl($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asUrl(null));
}
public function testAsImage()
{
$value = 'http://sample.com/img.jpg';
$this->assertSame("<img src=\"$value\" alt=\"\">", $this->formatter->asImage($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asImage(null));
}
......@@ -115,15 +195,35 @@ class FormatterTest extends TestCase
$this->assertSame('Yes', $this->formatter->asBoolean($value));
$value = "";
$this->assertSame('No', $this->formatter->asBoolean($value));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asBoolean(null));
}
// date format
public function testIntlAsDate()
{
$this->testAsDate();
}
public function testIntlAsTime()
{
$this->testAsTime();
}
public function testIntlAsDatetime()
{
$this->testAsDatetime();
}
public function testAsDate()
{
$value = time();
// $this->assertSame(date('M j, Y', $value), $this->formatter->asDate($value));
// test fails for "en-US" because travis has another version of ICU = other format
$this->assertSame(date('Y/m/d', $value), $this->formatter->asDate($value, 'Y/m/d'));
$this->assertSame(date('M j, Y', $value), $this->formatter->asDate($value));
$this->assertSame(date('Y/m/d', $value), $this->formatter->asDate($value, 'php:Y/m/d'));
$this->assertSame(date('n/j/y', $value), $this->formatter->asDate($value, 'short'));
$this->assertSame(date('F j, Y', $value), $this->formatter->asDate($value, 'long'));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDate(null));
......@@ -133,7 +233,7 @@ class FormatterTest extends TestCase
{
$value = time();
$this->assertSame(date('g:i:s A', $value), $this->formatter->asTime($value));
$this->assertSame(date('n:i:s A', $value), $this->formatter->asTime($value, 'n:i:s A'));
$this->assertSame(date('n:i:s A', $value), $this->formatter->asTime($value, 'php:n:i:s A'));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asTime(null));
}
......@@ -141,115 +241,21 @@ class FormatterTest extends TestCase
{
$value = time();
$this->assertSame(date('M j, Y g:i:s A', $value), $this->formatter->asDatetime($value));
$this->assertSame(date('Y/m/d h:i:s A', $value), $this->formatter->asDatetime($value, 'Y/m/d h:i:s A'));
$this->assertSame(date('Y/m/d h:i:s A', $value), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A'));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDatetime(null));
}
public function testAsInteger()
public function testAsTimestamp()
{
$value = 123;
$this->assertSame("$value", $this->formatter->asInteger($value));
$value = 123.23;
$this->assertSame("123", $this->formatter->asInteger($value));
$value = 'a';
$this->assertSame("0", $this->formatter->asInteger($value));
$value = -123.23;
$this->assertSame("-123", $this->formatter->asInteger($value));
$value = "-123abc";
$this->assertSame("-123", $this->formatter->asInteger($value));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asInteger(null));
}
public function testAsDouble()
{
$value = 123.12;
$this->assertSame("123.12", $this->formatter->asDouble($value));
$this->assertSame("123.1", $this->formatter->asDouble($value, 1));
$this->assertSame("123", $this->formatter->asDouble($value, 0));
$value = 123;
$this->assertSame("123.00", $this->formatter->asDouble($value));
$this->formatter->decimalSeparator = ',';
$this->formatter->thousandSeparator = '.';
$value = 123.12;
$this->assertSame("123,12", $this->formatter->asDouble($value));
$this->assertSame("123,1", $this->formatter->asDouble($value, 1));
$this->assertSame("123", $this->formatter->asDouble($value, 0));
$value = 123123.123;
$this->assertSame("123.123,12", $this->formatter->asDouble($value));
$this->assertSame("123123,12", $this->formatter->asDouble($value, 2, null, false));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDouble(null));
}
public function testAsNumber()
{
$value = 123123.123;
$this->assertSame("123,123", $this->formatter->asNumber($value));
$this->assertSame("123,123.12", $this->formatter->asNumber($value, 2));
$this->formatter->decimalSeparator = ',';
$this->formatter->thousandSeparator = ' ';
$this->assertSame("123 123", $this->formatter->asNumber($value));
$this->assertSame("123 123,12", $this->formatter->asNumber($value, 2));
$this->formatter->thousandSeparator = '';
$this->assertSame("123123", $this->formatter->asNumber($value));
$this->assertSame("123123,12", $this->formatter->asNumber($value, 2));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asNumber(null));
}
public function testAsDecimal()
{
$value = '123';
$this->assertSame($value, $this->formatter->asDecimal($value));
$value = '123456';
$this->assertSame("123,456", $this->formatter->asDecimal($value));
$value = '-123456.123';
$this->assertSame("-123,456.123", $this->formatter->asDecimal($value));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDecimal(null));
}
public function testAsCurrency()
{
$value = '123';
$this->assertSame('$123.00', $this->formatter->asCurrency($value));
$value = '123.456';
$this->assertSame("$123.46", $this->formatter->asCurrency($value));
// Starting from ICU 52.1, negative currency value will be formatted as -$123,456.12
// see: http://source.icu-project.org/repos/icu/icu/tags/release-52-1/source/data/locales/en.txt
// $value = '-123456.123';
// $this->assertSame("($123,456.12)", $this->formatter->asCurrency($value));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asCurrency(null));
}
$value = time();
$this->assertSame("$value", $this->formatter->asTimestamp($value));
$this->assertSame("$value", $this->formatter->asTimestamp((string) $value));
public function testAsScientific()
{
$value = '123';
$this->assertSame('1.23E2', $this->formatter->asScientific($value));
$value = '123456';
$this->assertSame("1.23456E5", $this->formatter->asScientific($value));
$value = '-123456.123';
$this->assertSame("-1.23456123E5", $this->formatter->asScientific($value));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asScientific(null));
}
$this->assertSame("$value", $this->formatter->asTimestamp(date('Y-m-d H:i:s', $value)));
public function testAsPercent()
{
$value = '123';
$this->assertSame('12,300%', $this->formatter->asPercent($value));
$value = '0.1234';
$this->assertSame("12%", $this->formatter->asPercent($value));
$value = '-0.009343';
$this->assertSame("-1%", $this->formatter->asPercent($value));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asPercent(null));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asTimestamp(null));
}
public function testFormat()
{
$value = time();
$this->assertSame(date('M j, Y', $value), $this->formatter->format($value, 'date'));
$this->assertSame(date('M j, Y', $value), $this->formatter->format($value, 'DATE'));
$this->assertSame(date('Y/m/d', $value), $this->formatter->format($value, ['date', 'Y/m/d']));
$this->setExpectedException('\yii\base\InvalidParamException');
$this->assertSame(date('Y-m-d', $value), $this->formatter->format($value, 'data'));
}
private function buildDateSubIntervals($referenceDate, $intervals)
{
......@@ -374,13 +380,103 @@ class FormatterTest extends TestCase
$this->assertSame('in 28 days', $this->formatter->asRelativeTime($dateThen, $dateNow));
}
public function testSetLocale(){
$value = '12300';
$this->formatter->setLocale('de-DE');
$this->assertSame('12.300,00', $this->formatter->asDouble($value, 2));
$value = time();
$this->assertSame(date('d.m.Y', $value), $this->formatter->asDate($value));
$this->formatter->setLocale('en-US');
}
// number format
// public function testAsInteger()
// {
// $value = 123;
// $this->assertSame("$value", $this->formatter->asInteger($value));
// $value = 123.23;
// $this->assertSame("123", $this->formatter->asInteger($value));
// $value = 'a';
// $this->assertSame("0", $this->formatter->asInteger($value));
// $value = -123.23;
// $this->assertSame("-123", $this->formatter->asInteger($value));
// $value = "-123abc";
// $this->assertSame("-123", $this->formatter->asInteger($value));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asInteger(null));
// }
//
// public function testAsDouble()
// {
// $value = 123.12;
// $this->assertSame("123.12", $this->formatter->asDouble($value));
// $this->assertSame("123.1", $this->formatter->asDouble($value, 1));
// $this->assertSame("123", $this->formatter->asDouble($value, 0));
// $value = 123;
// $this->assertSame("123.00", $this->formatter->asDouble($value));
// $this->formatter->decimalSeparator = ',';
// $this->formatter->thousandSeparator = '.';
// $value = 123.12;
// $this->assertSame("123,12", $this->formatter->asDouble($value));
// $this->assertSame("123,1", $this->formatter->asDouble($value, 1));
// $this->assertSame("123", $this->formatter->asDouble($value, 0));
// $value = 123123.123;
// $this->assertSame("123.123,12", $this->formatter->asDouble($value));
// $this->assertSame("123123,12", $this->formatter->asDouble($value, 2, null, false));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDouble(null));
// }
//
// public function testAsNumber()
// {
// $value = 123123.123;
// $this->assertSame("123,123", $this->formatter->asNumber($value));
// $this->assertSame("123,123.12", $this->formatter->asNumber($value, 2));
// $this->formatter->decimalSeparator = ',';
// $this->formatter->thousandSeparator = ' ';
// $this->assertSame("123 123", $this->formatter->asNumber($value));
// $this->assertSame("123 123,12", $this->formatter->asNumber($value, 2));
// $this->formatter->thousandSeparator = '';
// $this->assertSame("123123", $this->formatter->asNumber($value));
// $this->assertSame("123123,12", $this->formatter->asNumber($value, 2));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asNumber(null));
// }
//
// public function testAsDecimal()
// {
// $value = '123';
// $this->assertSame($value, $this->formatter->asDecimal($value));
// $value = '123456';
// $this->assertSame("123,456", $this->formatter->asDecimal($value));
// $value = '-123456.123';
// $this->assertSame("-123,456.123", $this->formatter->asDecimal($value));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDecimal(null));
// }
//
// public function testAsCurrency()
// {
// $value = '123';
// $this->assertSame('$123.00', $this->formatter->asCurrency($value));
// $value = '123.456';
// $this->assertSame("$123.46", $this->formatter->asCurrency($value));
// // Starting from ICU 52.1, negative currency value will be formatted as -$123,456.12
// // see: http://source.icu-project.org/repos/icu/icu/tags/release-52-1/source/data/locales/en.txt
//// $value = '-123456.123';
//// $this->assertSame("($123,456.12)", $this->formatter->asCurrency($value));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asCurrency(null));
// }
//
// public function testAsScientific()
// {
// $value = '123';
// $this->assertSame('1.23E2', $this->formatter->asScientific($value));
// $value = '123456';
// $this->assertSame("1.23456E5", $this->formatter->asScientific($value));
// $value = '-123456.123';
// $this->assertSame("-1.23456123E5", $this->formatter->asScientific($value));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asScientific(null));
// }
//
// public function testAsPercent()
// {
// $value = '123';
// $this->assertSame('12,300%', $this->formatter->asPercent($value));
// $value = '0.1234';
// $this->assertSame("12%", $this->formatter->asPercent($value));
// $value = '-0.009343';
// $this->assertSame("-1%", $this->formatter->asPercent($value));
// $this->assertSame($this->formatter->nullDisplay, $this->formatter->asPercent(null));
// }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment