Commit 0995a740 by Erik_r

Refactored formatter class #2359 which works with or without intl extension. Use…

Refactored formatter class #2359 which works with or without intl extension. Use PHP format patterns alsow with intl. Class is compatible with previous version.
parent ebf0cb55
Formatter
=========
Formatter is a helper component to format machine readable data of type date, time, different number types
in user readable formats. Most of this types are in countries differently formatted (eg. date: US -> '10/31/2014,
or DE -> '31.10.2014' or ISO -> '2014-10-31'). Same with decimals and currency values (eg. currency: US-> '$ 13,250.22' or
de-DE -> '13.250,22 €' or de-CH ->'CHF 13'250.22')
Formatter supports unformatting also. A localized formatted date or number can be unformatted into a machine readable
type (eg. '13.250,22 €' -> '13250.22')
This formatter version is merged from old `yii\base\formatter` and `yii\i18n\formatter` which supports localized formatting
and "english only" formatting.
Formatter uses the php extension "intl" if the extension is loaded. "Intl" uses [ICU standard](http://site.icu-project.org/) driven
by IBM. "intl" internally knows all formats of all countries and it translates month or day names into the corrcect language.
Unfortunately ICU don't use same format patterns like php (eg. ICU: 'yyyy-mm-dd' php: 'Y-m-d' or icu: 'yy-m-d' php: 'y-n-j').
Therefore formatter class has built in a pattern conversions from php to icu or icu to php. Formatter communicates in their interface
functions per standard with php patterns, but it's also possible to communicate with icu patterns.
If "intl" isn't loaded formatter works also in the same way. Even the named date, time or datetime formats from icu "short", "medium", "long"
and "full" are supported. Without a separate localized format definition US formats are used. Formatter provides a possibility to enter
localized format patterns in an array (class formatDefs). Formatter uses this definitions but can't translate month or day names into the
correct language.
If the application should support localized outputs "intl" extension should be enabled in php.ini. If Apache (xampp on windows only) doesn't
start correctly then you must install a library of Microsoft ([Visual C++ Redistributable](http://www.microsoft.com/de-de/download/details.aspx?id=30679))
Installation / Configuration
----------------------------
Formatter class must be registered in Yii config (eg. app/config/web.php) in section 'components'. The class must be specified. All other parameters are
optional. The following example shows all parameters and explain their default values. In most cases default values are ideal.
```php
'components' => [
'formatter' => [
'class' => 'guggach\helpers\Formatter',
// 'dateFormat' => 'medium', // default: 'medium'
// 'timeFormat' => 'medium', // default: 'medium'
// 'datetimeFormat' => 'medium' // default: 'medium'
// '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']
// 'local' => 'de-CH' // default: yii::$app->locale
// 'timezone' => 'Europe/Berlin' // default: yii::$app->timezone
// 'nullDisplay => '<span class="not-set">(not set)</span>' // default '(not set)' translated with yii::t
// 'booleanFormat' => ['No', 'Yes'] // default: ['No', 'Yes'] translated with yii::t
// 'numberFormatOptions' => [] // see intl NumberFormatter
// 'numberTextFormatOptions' => [] // see intl NumberFormatter
// 'decimalSeparator' => '.' // default ICU locale definition or FormatDefs class
// 'thousandSeparator' => ',' // default ICU locale definition or FormatDefs class
// 'currencyCode' => 'USD' // default ICU locale definition or FormatDefs class
// 'RoundingIncrement' => 0.01 // default to number of decimals, currency = 0.01 (except Switzerland 0.05)
// 'sizeFormat' => [] // default ['base' = 1024 , 'decimals' = 2, 'decimalSeparator' = null]
];
```
Details for each parameter are described in formatter.php.
Using formatter
---------------
Formatter is a general component which is registered in `yii::$app->formatter`. Mostly used funtions are `yii::$app->formatter->format()`
or `yii::$app->formatter->unformat()`.
Usage in Code, example:
$formattedValueString = yii::$app->formatter->format($value, ['date' , 'd-m-y' , 'php']);
$value = yii::$app->formatter->unformat($formattedValueString, ['currency']);
Format and unformat function has minimal two parameter like
`(un)format( mixed $value , [ 'format as' , 'optional 1', 'optional 2' ... ])`
1. $value (must): machine readable date, time, datetime or number which hast to be formatted.
2. 'format as' (must): defines what type the value is and what kind of format is expected.
3. 'Option n': The number of paramters and the content is dependant of 'format as'. Details see in further chapters.
In following chapters all formatters are described in detail with input parameters.
###Format or unformat as 'date' or 'time or 'datetime
`format(date (mixed), ['date'/'time'/'datetime' , 'target format pattern', 'input format pattern' , 'format type'])`
####Input:
1. date mixed (must):
It can be a Unix timestamp, DateTime object or a date string. A string must be in ISO format ('2014-10-05') or in local
date format (de-DE: '05.10.2014'). If another format is given the 'input format pattern' must be specified (eg. US: 'M/d/Y')
2. 'date'/'time'/'datetime' (must):
A timestamp (DateTime object) can be formatted in a date (eg. '2014-10-05') or a time (eg. 15:20:30) or in a
datetime (eg. '2014-10-05 15:20:30'). This parameter specifies which of these three formats should be done.
3. 'target format pattern' (optinal):
Formatter has four predefined format patterns: `short` ('y-n-j' = 14-10-25), `medium`('Y-m-d' = 2014-10-25), `long` ('F j, Y' = October
25, 2014) or 'full' ('l, F j, Y' = Saturday, October 25, 2014). An individual format can be defined by a pattern string like 'd. F Y' ( 25. October 2014).
The individual pattern string is per default in 'php' syntax. Alternatively ICU pattern (dd. MMMM yyyy) could be used. (see format type)
4. 'input format pattern' (optional):
If input date is a string formatter convert into a DateTime object internally. Formatter recognize ISO format (2014-10-25) or locale format.
All other formats will produce a false result unless the input format is defined in this parameter. Default format pattern is php.
5. 'format type' (optional):
Per default formatter communicates with 'php' format patterns independent if ICU is used or not. This makes format handling in Yii easier because
a developer is concentrating to one format all over the application. Nevertheless ICU patterns can be used if this parameter is 'icu'.
####Output:
Formatted string like '25th October 2014'.
`unformat(date (string), ['date'/'time'/'datetime', 'target format', 'input format pattern', 'format type'])`
####Input:
1. date as string:
Formatted date as string. The string must be in ISO format ('2014-10-05') or in local
date format (de-DE: '05.10.2014'). If another format is given the 'input format pattern' must be specified (eg. US: 'M/d/Y').
2. 'date'/'time'/'datetime' (must):
Defines if input is a date or a time or a datetime string.
3. 'target format' (optional):
Valid values are `'db'`or `'timestamp'`. Default is 'db' because a user readable date string must be stored in a database. Databases mostly
accept ISO format ('2014-10-25') only. If format is different the database format can be configured in variable `dbFormat` (array).
4. 'input format pattern' (optional):
see format date function
5. 'format type' (optional):
see format date function
###Format as Timestamp
`format ('date'/'time'/'datetime' (string), ['timestamp', 'input format pattern'])`
####Input:
Parameter see 'format date'.
####Output:
Long integer (64bit or float) with Unix Timestamp in seconds from 01/01/1970.
###Format or unformat as Integer
`format(value (mixed), ['integer' , 'thousandSeparator'])`
`unformat(value (string), 'integer')`
####Input:
1. value (integer, float, numeric string) (must):
In format function a numeric string or a float or an integer is necessary. A float with decimals will be mathematically rounded to an integer.
The unformat function needs a string which can have thousand separators but it must be numeric.
2. 'integer' (string)(must):
This is the name of formatting function which is used.
3. 'thousandSeparator' (boolean) (optional):
Valid values are `true`or `false`. Default is `true`. If value is true the output is formatted with thousand separator concerning the locale
definition or the value of the variable 'thousandSeparator'.
####Output:
Formatted string like '23,456,698'.
###Format or unformat as Double, Number, Decimal
Double, Number, Decimal are all synonyms for floating numbers with decimals.
`format(value (mixed), ['double', decimals (int) , roundIncrement (float), grouping (boolean)`
`unformat(value (string), 'double')`
####Input:
1. value (float, numeric string) (must):
In format function a numeric string or a float is necessary. A float with decimals will be mathematically rounded to the number of decimals.
The unformat function needs a string which can have thousand separators but it must be numeric.
2. 'double' (string) (must):
This is the name of the formatting function. As synonym 'decimals' and 'number' could be used.
3. decimals (integer) (optional):
Number of decimals after comma. Per default 2 is set. If the number of decimals is less than 6 zeros are filled until number of decimals
(eg. decimals = 4 -> 3.42 -> 3.4200).
4. RoundIncrement (float) (optinal):
If roundIncrement isn't set the float will be rounded to last requested decimal with mathematical rule (eg. decimals = 3 -> 3.45662 --> 3.457).
If roundIncrement is set to '0.01' float will be rounded to this value (eg. decimals = 3 -> 3.45662 -> 3.46000).
5. Grouping (boolean) (optional):
If value is true the float will be formatted with thousand separator otherwise not. Default is true.
####Output:
Formatted string like '3,456,698.65'
###Format or unformat as currency
`format(value (mixed), ['currency', 'currency code' (string) , roundIncrement (float), grouping (boolean)`
`unformat(value (string), 'currency')`
###Input:
1. value (float, numeric string) (must):
In format function a numeric string or a float is necessary. The currency amount with decimals will be mathematically rounded to two decimals.
The unformat function needs a string which can have thousand separators but it must be numeric.
2. 'currency' (string) (must):
This is the name of the formatting function.
3. 'currency code' (string) (optional):
Normally currency code is provided by ICU from locale setting. If another currency is needed the code as string can be set here.
4. RoundIncrement (float) (optinal):
If roundIncrement isn't set the float will be rounded to last requested decimal with mathematical rule.
If roundIncrement is set to '0.05' (Switzerland with 5 cents only) float will be rounded to this value (eg. 3.26 -> 3.25 or 3.275 -> 3.30).
5. Grouping (boolean) (optional):
If value is true the float will be formatted with thousand separator otherwise not. Default is true.
####Output:
Formatted string like '$ 13,256.23'
###Format or unformat as scientific
`format(value (mixed), ['scientific', decimals (integer))`
`unformat(value (string), 'scientific')`
Scientific formats a float to a scientifc string like '23216' to '2.32166E4'.
###Format or unformat as percent
`format(value (mixed), ['percent', decimals (integer) , grouping (boolean)`
`unformat(value (string), 'percent')`
###Input:
1. value (float, numeric string) (must):
In format function a numeric string or a float is necessary. Value is a factor like '0.75' -> '75%'.
The unformat function needs a string which can have thousand separators but it must be numeric. It will be converted back to a factor. '75%' -> '0.75'
2. 'percent':
This is the name of the formatting function.
3. decimals (integer) (optional):
Number of decimals. The formatter rounds a float to the number of decimals.
4. Grouping (boolean) (optional):
If value is true the percent value will be formatted with thousand separator otherwise not. Default is true.
####Output:
Formatted string like '75.05%'. The unformatter produces a float as factor like 0.7505.
###Further formatters
Formatter has formatting rules for Text, HTML, Email, Boolean etc.
`format(value (mixed), 'name of formatter')`
Formatters are:
`boolean:` Ouput is a string with 'Yes' or 'No' translated to locale setting.
`email:` Converts an email address to a 'mailto' link.
`html:` Converts a string with html-purifier to avoid XSS attacks.
`image:` Formats a html image tag around a path to image.
`NText:` Formats the value as an HTML-encoded plain text with newlines converted into breaks.
`Paragraphs:` Formats the value as HTML-encoded text paragraphs. Each text paragraph is enclosed within a `<p>` tag.
`raw:` Formats the value as is without any formatting. Null values are showed as 'not set'.
`size:` Formats a number as byte, kilobyte, megabyte etc. depending on the size of the number. Normally 'Mb' is given unless optional parameter is true.
`text:` Formats the value as an HTML-encoded plain text.
`url:` Formats the value as a hyperlink. If necessary it adds 'https://'.
Other functions
---------------
###getLocale()
Shows the current used locale setting in format like 'de-DE'.
###setLocale($locale)
Per default formatter uses locale information from application configuration. If another local definition is requested on the fly this function changes the internal pattern settings, decimal sign and thousand separator to the requested locale. It return this formatter object to enable chaining.
###getDecimalSeparator()
Shows the current separator for decimal number.
###setDecimalSeparator($sign)
Per default formatter uses the decimal separator sign from ICU concerning locale setting. With setDecimalSeparator the value can be overridden.
###getThousandSeparator()
Shows the current separator for thousand grouping.
###SetThousandSeparator($sign)
Per default formatter uses the thousand separator sign from ICU concerning locale setting. With setThousandSeparator the value can be overridden.
###convertPatternPhpToIcu($pattern, $type)
Converts a php date or time format pattern from PHP syntax to ICU syntax (eg. 'Y-m-d' -> 'yyyy-MM-dd'). If pattern is 'short', 'medium', 'long' or 'full' then the parameter 'type' must be defined like 'date', 'time' or 'datetime'. In this case the function delivers the correct ICU pattern (eg. 'medium' and 'date' -> 'dd-MM-yyyy'.
###convertPatternIcuToPhp($pattern, $type)
Converts a ICU date or time format pattern from ICU syntax to PHP syntax (eg. 'yyyy-MM-dd' -> 'Y-m-d'). If pattern is 'short', 'medium', 'long' or 'full' then the parameter 'type' must be defined like 'date', 'time' or 'datetime'. In this case the function delivers the correct PHP pattern (eg. 'medium' and 'date' -> 'd-m-Y'.
...@@ -4,6 +4,7 @@ Yii Framework 2 Change Log ...@@ -4,6 +4,7 @@ Yii Framework 2 Change Log
2.0.0-rc under development 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 #1263: Fixed the issue that Gii and Debug modules might be affected by incompatible asset manager configuration (qiangxue)
- Bug #2563: Theming is not working if the path map of the theme contains ".." or "." in the paths (qiangxue) - Bug #2563: Theming is not working if the path map of the theme contains ".." or "." in the paths (qiangxue)
- Bug #2801: Fixed the issue that GridView gets footer content before data cells content (ElisDN) - Bug #2801: Fixed the issue that GridView gets footer content before data cells content (ElisDN)
......
...@@ -5,16 +5,23 @@ ...@@ -5,16 +5,23 @@
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\base; //namespace yii\base;
namespace guggach\helpers;
use Yii; use Yii;
use DateTime; use DateTime;
use IntlDateFormatter;
use NumberFormatter;
use yii\helpers\HtmlPurifier; use yii\helpers\HtmlPurifier;
use yii\helpers\Html; use yii\helpers\Html;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use guggach\helpers\FormatDefs;
/** /**
* Formatter provides a set of commonly used data formatting methods. * Formatter provides a set of commonly used data formatting methods.
* *
* The formatting methods provided by Formatter are all named in the form of `asXyz()`. * The formatting methods provided by Formatter are all named in the form of `asXyz()`.
* The behavior of some of them may be configured via the properties of Formatter. For example, * The behavior of some of them may be configured via the properties of Formatter. For example,
* by configuring [[dateFormat]], one may control how [[asDate()]] formats the value into a date string. * by configuring [[dateFormat]], one may control how [[asDate()]] formats the value into a date string.
...@@ -24,10 +31,49 @@ use yii\helpers\Html; ...@@ -24,10 +31,49 @@ use yii\helpers\Html;
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ *
class Formatter extends Component * 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.
*
* 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.
* As a constraint month and day names are in english only.
*
* The communication with formatter class is per standard with php format patterns. They are converted internally to
* icu format patterns. Further it supports for date, time and datetime the named patterns "short", "medium", "long" and
* "full" plus "db" (database), also if "intl" isn't loaded. The format function has an option parameter to use "icu"
* format patterns.
*
* 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
{ {
/** /**
* @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. * @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) * 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`. * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
...@@ -37,16 +83,28 @@ class Formatter extends Component ...@@ -37,16 +83,28 @@ class Formatter extends Component
public $timeZone; public $timeZone;
/** /**
* @var string the default format string to be used to format a date using PHP date() function. * @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 = 'Y-m-d'; public $dateFormat = 'medium'; // php:'Y-m-d';
/** /**
* @var string the default format string to be used to format a time using PHP date() function. * @var string the default format string to be used to format a time using PHP date() function.
* see "$dateFormat"
*/ */
public $timeFormat = 'H:i:s'; 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. * @var string the default format string to be used to format a date and time using PHP date() function.
* see "$dateFormat"
*/ */
public $datetimeFormat = 'Y-m-d H:i:s'; public $datetimeFormat = 'medium'; // php: 'Y-m-d H:i:s';
/**
*
* @var string default format pattern for database requested format.
*/
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'];
/** /**
* @var string the text to be displayed when formatting a null. Defaults to '<span class="not-set">(not set)</span>'. * @var string the text to be displayed when formatting a null. Defaults to '<span class="not-set">(not set)</span>'.
*/ */
...@@ -57,6 +115,22 @@ class Formatter extends Component ...@@ -57,6 +115,22 @@ class Formatter extends Component
*/ */
public $booleanFormat; public $booleanFormat;
/** /**
* @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)
* for the possible options. This property is used by [[createNumberFormatter]] when
* creating a new number formatter to format decimals, currencies, etc.
*/
public $numberFormatOptions = [];
/**
* @var array the text options to be set for the NumberFormatter objects (eg. Negative sign). Please refer to
* [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
* for the possible options. This property is used by [[createNumberFormatter]] when
* creating a new number formatter to format decimals, currencies, etc.
*
* Default value: GOUPING_USED = 1 / MAX_FRACTION_DIGITS = 3 / GROUPING_SIZE = 3 / ROUNDING_MODE = 4
*/
public $numberTextFormartOptions = [];
/**
* @var string the character displayed as the decimal point when formatting a number. * @var string the character displayed as the decimal point when formatting a number.
* If not set, "." will be used. * If not set, "." will be used.
*/ */
...@@ -67,9 +141,25 @@ class Formatter extends Component ...@@ -67,9 +141,25 @@ class Formatter extends Component
*/ */
public $thousandSeparator; 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.
*/
public $currencyCode;
/**
*
* @var type 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
*/
public $roundingIncrement;
public $roundingIncrCurrency;
/**
* @var array the format used to format size (bytes). Three elements may be specified: "base", "decimals" and "decimalSeparator". * @var array the format used to format size (bytes). Three elements may be specified: "base", "decimals" and "decimalSeparator".
* They correspond to the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte, defaults to 1024), * They correspond to the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte, defaults to 1024),
* the number of digits after the decimal point (defaults to 2) and the character displayed as the decimal point. * the number of digits after the decimal point (defaults to 2) and the character displayed as the decimal point.
*/ */
public $sizeFormat = [ public $sizeFormat = [
'base' => 1024, 'base' => 1024,
...@@ -78,6 +168,68 @@ class Formatter extends Component ...@@ -78,6 +168,68 @@ class Formatter extends Component
]; ];
/** /**
* @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.
*
*/
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,
];
/**
*
* @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. * Initializes the component.
*/ */
public function init() public function init()
...@@ -85,6 +237,10 @@ class Formatter extends Component ...@@ -85,6 +237,10 @@ class Formatter extends Component
if ($this->timeZone === null) { if ($this->timeZone === null) {
$this->timeZone = Yii::$app->timeZone; $this->timeZone = Yii::$app->timeZone;
} }
if ($this->locale === null) {
$this->locale = Yii::$app->language;
}
if (empty($this->booleanFormat)) { if (empty($this->booleanFormat)) {
$this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')]; $this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')];
...@@ -92,9 +248,33 @@ class Formatter extends Component ...@@ -92,9 +248,33 @@ class Formatter extends Component
if ($this->nullDisplay === null) { if ($this->nullDisplay === null) {
$this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)') . '</span>'; $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';
}
} }
/** /**
* Formats the value based on the given format type. * Formats the value based on the given format type.
* This method will call one of the "as" methods available in this class to do the formatting. * This method will call one of the "as" methods available in this class to do the formatting.
* For type "xyz", the method "asXyz" will be used. For example, if the format is "html", * For type "xyz", the method "asXyz" will be used. For example, if the format is "html",
...@@ -103,7 +283,8 @@ class Formatter extends Component ...@@ -103,7 +283,8 @@ class Formatter extends Component
* @param string|array $format the format of the value, e.g., "html", "text". To specify additional * @param string|array $format the format of the value, e.g., "html", "text". To specify additional
* parameters of the formatting method, you may use an array. The first element of the array * parameters of the formatting method, you may use an array. The first element of the array
* specifies the format name, while the rest of the elements will be used as the parameters to the formatting * 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']` will cause the invocation of `asDate($value, 'Y-m-d')`. * method. For example, a format of `['date', 'Y-m-d', 'php']` will cause the invocation of `asDate($value, 'Y-m-d', 'php')`.
* For more details see asXXX functions.
* @return string the formatting result * @return string the formatting result
* @throws InvalidParamException if the type is not supported by this class. * @throws InvalidParamException if the type is not supported by this class.
*/ */
...@@ -128,6 +309,477 @@ class Formatter extends Component ...@@ -128,6 +309,477 @@ class Formatter extends Component
} }
} }
/**
* 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.
*/
public function unformat($value, $format)
{
if (is_array($format)) {
if (!isset($format[0])) {
throw new InvalidParamException('The $format array must contain at least one element.');
}
$f = $format[0];
$format[0] = $value;
$params = $format;
$format = $f;
} else {
$params = [$value];
}
$method = 'uf' . $format;
if ($this->hasMethod($method)) {
return call_user_func_array([$this, $method], $params);
} else {
throw new InvalidParamException("Unknown type: $format");
}
}
/**
* 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
*/
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();
}
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'
}
}
} elseif (strtolower($pattern) === 'db'){
return $this->dbFormat[strtolower($type)];
}
return strtr($pattern, [
'dd' => 'd', // day with leading zeros
'd' => 'j', // day without leading zeros
'E' => 'D', // day written in short form eg. Sun
'EE' => 'D',
'EEE' => 'D',
'EEEE' => 'l', // day fully written eg. Sunday
'e' => 'N', // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
'ee' => 'N', // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
// engl. ordinal st, nd, rd; it's not support by ICU but we added
'D' => 'z', // day of the year 0 to 365
'w' => 'W', // ISO-8601 week number of year, weeks starting on Monday
'W' => '', // week of the current month; isn't supported by php
'F' => '', // Day of Week in Month. eg. 2nd Wednesday in July
'g' => '', // Modified Julian day. This is different from the conventional Julian day number in two regards.
'M' => 'n', // Numeric representation of a month, without leading zeros
'MM' => 'm', // Numeric representation of a month, with leading zeros
'MMM' => 'M', // A short textual representation of a month, three letters
'MMMM' => 'F', // A full textual representation of a month, such as January or March
'Q' => '', // number of quarter not supported in php
'QQ' => '', // number of quarter '02' not supported in php
'QQQ' => '', // quarter 'Q2' not supported in php
'QQQQ' => '', // quarter '2nd quarter' not supported in php
'QQQQQ' => '', // number of quarter '2' not supported in php
'Y' => 'Y', // 4digit year number eg. 2014
'y' => 'Y', // 4digit year also
'yyyy' => 'Y', // 4digit year also
'yy' => 'y', // 2digit year number eg. 14
'r' => '', // related Gregorian year, not supported by php
'G' => '', // ear designator like AD
'a' => 'a', // Lowercase Ante meridiem and Post
'h' => 'g', // 12-hour format of an hour without leading zeros 1 to 12h
'K' => 'g', // 12-hour format of an hour without leading zeros 0 to 11h, not supported by php
'H' => 'G', // 24-hour format of an hour without leading zeros 0 to 23h
'k' => 'G', // 24-hour format of an hour without leading zeros 1 to 24h, not supported by php
'hh' => 'h', // 12-hour format of an hour with leading zeros, 01 to 12 h
'KK' => 'h', // 12-hour format of an hour with leading zeros, 00 to 11 h, not supported by php
'HH' => 'H', // 24-hour format of an hour with leading zeros, 00 to 23 h
'kk' => 'H', // 24-hour format of an hour with leading zeros, 01 to 24 h, not supported by php
'm' => 'i', // Minutes without leading zeros, not supported by php
'mm' => 'i', // Minutes with leading zeros
's' => 's', // Seconds, without leading zeros, not supported by php
'ss' => 's', // Seconds, with leading zeros
'SSS' => '', // millisecond (maximum of 3 significant digits), not supported by php
'A' => '', // milliseconds in day, not supported by php
'Z' => 'O', // Difference to Greenwich time (GMT) in hours
'ZZ' => 'O', // Difference to Greenwich time (GMT) in hours
'ZZZ' => 'O', // Difference to Greenwich time (GMT) in hours
'z' => 'T', // Timezone abbreviation
'zz' => 'T', // Timezone abbreviation
'zzz' => 'T', // Timezone abbreviation
'zzzz' => 'T', // Timzone full name, not supported by php
'V' => 'e', // Timezone identifier eg. Europe/Berlin
'VV' => 'e',
'VVV' => 'e',
'VVVV' => 'e'
]);
}
/**
* intlFormatter class (ICU based) and DateTime class don't have same format string.
* These format patterns are completely incompatible and must be converted.
*
* This method converts PHP formatted date, time or datetime string in
* an ICU (php intl) compatible format string.
*
* @param 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
*/
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].');
}
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 \guggach\helpers\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->decimalSeparator);
$this->setThousandSeparator($this->thousandSeparator);
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 \guggach\helpers\Formatter
*/
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 \guggach\helpers\Formatter
*/
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. * Formats the value as is without any formatting.
* This method simply returns back the parameter without any format. * This method simply returns back the parameter without any format.
...@@ -142,7 +794,11 @@ class Formatter extends Component ...@@ -142,7 +794,11 @@ class Formatter extends Component
return $value; return $value;
} }
public function ufRaw($value){
if ($value === $this->nullDisplay);
return null;
}
/** /**
* Formats the value as an HTML-encoded plain text. * Formats the value as an HTML-encoded plain text.
* @param mixed $value the value to be formatted * @param mixed $value the value to be formatted
...@@ -156,7 +812,12 @@ class Formatter extends Component ...@@ -156,7 +812,12 @@ class Formatter extends Component
return Html::encode($value); return Html::encode($value);
} }
public function ufText($value){
if ($value === Html::encode($this->nullDisplay)){
return null;
}
}
/** /**
* Formats the value as an HTML-encoded plain text with newlines converted into breaks. * Formats the value as an HTML-encoded plain text with newlines converted into breaks.
* @param mixed $value the value to be formatted * @param mixed $value the value to be formatted
...@@ -264,7 +925,16 @@ class Formatter extends Component ...@@ -264,7 +925,16 @@ class Formatter extends Component
return $value ? $this->booleanFormat[1] : $this->booleanFormat[0]; 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.');
}
}
/** /**
* Formats the value as a date. * Formats the value as a date.
* @param integer|string|DateTime $value the value to be formatted. The following * @param integer|string|DateTime $value the value to be formatted. The following
...@@ -274,22 +944,77 @@ class Formatter extends Component ...@@ -274,22 +944,77 @@ class Formatter extends Component
* - a string that can be parsed into a UNIX timestamp via `strtotime()` * - a string that can be parsed into a UNIX timestamp via `strtotime()`
* - a PHP DateTime object * - a PHP DateTime object
* *
* @param string $format the format used to convert the value into a date string. * @param string $targetFormat (optional): the format pattern used to convert the value into a date string.
* If null, [[dateFormat]] will be used. The format string should be one * 'short', 'medium', 'long', 'full' or pattern like 'j-n-Y'
* that can be recognized by the PHP `date()` function. * @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'
*
* @return string the formatted result * @return string the formatted result
* @see dateFormat * @see dateFormat
*/ */
public function asDate($value, $format = null) public function asDate($value, $targetFormat = 'date', $inputFormat = null, $formatType = 'php')
{ {
if ($value === null) { if ($value === null) {
return $this->nullDisplay; return $this->nullDisplay;
} }
$value = $this->normalizeDatetimeValue($value); $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;
}
return $this->formatTimestamp($value, $format === null ? $this->dateFormat : $format); if ($this->_intlLoaded){
if ($targetFormat === 'date') {
$targetFormat = $this->_dateFormatIcu;
} elseif ($targetFormat === 'db'){
$targetFormat = $this->convertPatternPhpToIcu($this->dbFormat['date']);
} else {
if ($formatType === 'php'){
$targetFormat = $this->convertPatternPhpToIcu($targetFormat, 'date');
}
}
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);
}
}
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');
}
} else { // icu format
$format = $this->convertPatternIcuToPhp($targetFormat, 'date');
}
}
$date = new DateTime('@'.$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 the value as a time. * Formats the value as a time.
* @param integer|string|DateTime $value the value to be formatted. The following * @param integer|string|DateTime $value the value to be formatted. The following
...@@ -305,14 +1030,68 @@ class Formatter extends Component ...@@ -305,14 +1030,68 @@ class Formatter extends Component
* @return string the formatted result * @return string the formatted result
* @see timeFormat * @see timeFormat
*/ */
public function asTime($value, $format = null) public function asTime($value, $targetFormat = 'time', $inputFormat = null, $formatType = 'php')
{ {
if ($value === null) { if ($value === null) {
return $this->nullDisplay; return $this->nullDisplay;
} }
$value = $this->normalizeDatetimeValue($value); $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 ($this->_intlLoaded){
if ($targetFormat === 'time') {
$targetFormat = $this->_timeFormatIcu;
} elseif ($targetFormat === 'db'){
$targetFormat = $this->convertPatternPhpToIcu($this->dbFormat['time']);
} else {
if ($formatType === 'php'){
$targetFormat = $this->convertPatternPhpToIcu($targetFormat, 'time');
}
}
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 ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}else {
if ($targetFormat === 'time') {
$targetFormat = $this->timeFormat;
} else {
if ($formatType === 'php'){
if (isset($this->_dateFormatsIcu[$targetFormat])){ // names like "short", "medium" etc. in $format
$format = $this->convertPatternIcuToPhp($targetFormat, 'time');
}
} else { // icu format
$format = $this->convertPatternIcuToPhp($targetFormat, 'time');
}
}
$date = new DateTime('@'.$value);
return $date->format($format);
}
return $this->formatTimestamp($value, $format === null ? $this->timeFormat : $format); }
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 );
}
} }
/** /**
...@@ -330,115 +1109,471 @@ class Formatter extends Component ...@@ -330,115 +1109,471 @@ class Formatter extends Component
* @return string the formatted result * @return string the formatted result
* @see datetimeFormat * @see datetimeFormat
*/ */
public function asDatetime($value, $format = null) public function asDatetime($value, $targetFormat = 'datetime', $inputFormat = null, $formatType = 'php')
{ {
if ($value === null) { if ($value === null) {
return $this->nullDisplay; return $this->nullDisplay;
} }
$value = $this->normalizeDatetimeValue($value); $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;
}
return $this->formatTimestamp($value, $format === null ? $this->datetimeFormat : $format); 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 (isset($this->_dateFormatsIcu[$targetFormat])) {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$targetFormat], $this->_dateFormats[$targetFormat], $this->timeZone);
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($targetFormat);
}
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}else {
if ($targetFormat === 'datetime') {
$targetFormat = $this->datetimeFormat;
} 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);
}
}
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);
} 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 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
*/
public function asTimestamp($value, $inputFormat = null){
return $this->normalizeDatetimeValue($value, $inputFormat);
}
/**
* Normalizes the given datetime value as one that can be taken by various date/time formatting methods. * Normalizes the given datetime value as one that can be taken by various date/time formatting methods.
* *
* @param mixed $value the datetime value to be normalized. * @param mixed $value the datetime value to be normalized.
* @return integer the normalized datetime value * @param string $inputPattern format of $value if not database format or local format.
* @return float the normalized datetime value (int64)
*/ */
protected function normalizeDatetimeValue($value) protected function normalizeDatetimeValue($value, $inputPattern = null, $patternFor = 'php')
{ {
if ($value === null){
return null;
}
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['date'] = $this->dateFormat;
$FormatPatterns['time'] = $this->timeFormat;
$FormatPatterns['datetime'] = $this->datetimeFormat;
}
if (is_string($value)) { if (is_string($value)) {
if (is_numeric($value) || $value === '') { if (is_numeric($value) || $value === '') {
$value = (double)$value; $value = (double)$value;
} else { } else {
try { try {
$date = new DateTime($value); /** $date = new DateTime($value); ==> constructor crashes with
} catch (\Exception $e) { * an invalid date in $value (eg. 2014-06-35) and can't be
return false; * 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;
}
} catch (Exception $e) {
return null;
}
if ($date === false){
return null;
} }
$value = (double)$date->format('U'); $value = (double)$date->format('U');
} }
return $value; return $value;
} elseif ($value instanceof DateTime || $value instanceof \DateTimeInterface) {
} elseif ($value instanceof DateTime || $value instanceof \DateTimeInterface) {
return (double)$value->format('U'); return (double)$value->format('U');
} else { } else {
return (double)$value; return (double)$value;
} }
}
/**
* @param integer $value normalized datetime value
* @param string $format the format used to convert the value into a date string.
* @return string the formatted result
*/
protected function formatTimestamp($value, $format)
{
$date = new DateTime(null, new \DateTimeZone($this->timeZone));
$date->setTimestamp($value);
return $date->format($format);
} }
/** /**
* Formats the value as an integer. * Formats the value as an integer and rounds decimals with math rule
* @param mixed $value the value to be formatted * @param mixed $value the value to be formatted
* @return string the formatting result. * @return string the formatting result.
*/ */
public function asInteger($value) public function asInteger($value, $grouping = true) {
{ $format = null;
if ($value === null) { if ($value === null) {
return $this->nullDisplay; return $this->nullDisplay;
} }
if (is_string($value) && preg_match('/^(-?\d+)/', $value, $matches)) { if (is_string($value)) {
return $matches[1]; $value = (float) $value;
}
$value = round($value, 0);
if ($this->_intlLoaded){
$f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $format);
if ($grouping === false){
$f->setAttribute(NumberFormatter::GROUPING_USED, false);
}
return $f->format($value, NumberFormatter::TYPE_INT64);
} else { } else {
$value = (int) $value; $grouping = $grouping === true ? $this->thousandSeparator : '';
return number_format($value, 0, $this->decimalSeparator, $grouping);
return "$value";
} }
} }
public function ufInteger($value){
if ($value === null) {
return null;
}
$value = $this->unformatNumber($value, 'int');
return round($value , 0);
}
/** /**
* Formats the value as a double number. * Formats the value as a double number.
* Property [[decimalSeparator]] will be used to represent the decimal point. * Property [[decimalSeparator]] will be used to represent the decimal point. The
* value is rounded automatically to the defined decimal digits.
*
* PHP and ICU has different behaviour about number of zeros in fraction digits.
* PHP fills up to defined decimals (eg. 2.500000 [6]) while ICU hide unnecessary digits.
* (eg. 2.5 [6]). Until 5 fractional digits in this function is defined to 5 up with zeros.
*
* @param mixed $value the value to be formatted * @param mixed $value the value to be formatted
* @param integer $decimals the number of digits after the decimal point * @param integer or string $decimals the number of digits after the decimal point if the value is an integer
* otherwise it's is a format pattern string (this works only with intl [icu]).
* @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 boolean $grouping Per standard numbers are grouped in thousands. False = no grouping
* @return string the formatting result. * @return string the formatting result.
* @see decimalSeparator * @see decimalSeparator
* @see thousandSeparator
*/ */
public function asDouble($value, $decimals = 2) public function asDouble($value, $decimals = 2, $roundIncr = null, $grouping = true)
{ {
$format = null;
if(is_numeric($decimals)){
$decimals = intval($decimals); // number of digits after decimal
} else {
$format = $decimals; // format pattern for ICU only
}
if ($value === null) { if ($value === null) {
return $this->nullDisplay; return $this->nullDisplay;
} }
if ($this->decimalSeparator === null) { if (is_string($value)){
return sprintf("%.{$decimals}f", $value); if (is_numeric($value)){
$value = (float)$value;
} else {
throw new InvalidParamException('"' . $value . '" is not a numeric value.');
}
}
// if (true === false){
if ($this->_intlLoaded){
$f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $format);
$f->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
if ($decimals <= 5){
$f->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
}
if ($roundIncr == null and $this->roundingIncrement != null){
$roundIncr = $this->roundingIncrement;
}
if ($roundIncr != null){
$f->setAttribute(NumberFormatter::ROUNDING_INCREMENT, $roundIncr);
}
if ($grouping === false){
$f->setAttribute(NumberFormatter::GROUPING_USED, false);
}
return $f->format($value);
} else { } else {
return str_replace('.', $this->decimalSeparator, sprintf("%.{$decimals}f", $value));
if ($roundIncr !== null){
$part = explode('.', (string)$roundIncr);
if ((string)$roundIncr != '0.05'){ // exception for Swiss rounding.
$roundIncr = $decimals;
if (intval($part[0]) > 0){
if (substr($part[0], 0, 1) === '1'){
$roundIncr = (strlen($part[0]) -1) * -1 ;
} else {
throw new InvalidParamException('$roundIncr must have "1" only eg. 0.01 or 10 but not 0.02 or 20');
}
} elseif (isset($part[1]) and intval($part[1])>0) {
if (substr($part[1], -1) === '1'){
$roundIncr = strlen($part[1]);
} else {
throw new InvalidParamException('$roundIncr must have "1" only eg. 0.01 or 10 but not 0.02 or 20');
}
}
$value = round($value, $roundIncr);
} else {
$value = round($value/5,2)*5;
}
}
$grouping = $grouping === true ? $this->thousandSeparator : '';
return number_format($value, $decimals, $this->decimalSeparator, $grouping);
}
}
public function ufDouble($value){
if ($value === null){
return null;
} }
return $this->unformatNumber($value);
} }
/** /**
* Formats the value as a number with decimal and thousand separators. * Formats the value as a number with decimal and thousand separators.
* This method calls the PHP number_format() function to do the formatting. * This method is a synomym for asDouble.
* @param mixed $value the value to be formatted * @param mixed $value the value to be formatted
* @param integer $decimals the number of digits after the decimal point * @param integer $decimals the number of digits after the decimal point
* @return string the formatted result * @return string the formatted result
* @see decimalSeparator * @see decimalSeparator
* @see thousandSeparator * @see thousandSeparator
*/ */
public function asNumber($value, $decimals = 0) public function asNumber($value, $decimals = 0, $roundIncr = null, $grouping = true)
{ {
return 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 = 2, $roundIncr = null, $grouping = true)
{
return 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 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 asPercent($value, $decimals = 2, $grouping = true)
{
$format = null;
if(is_numeric($decimals)){
$decimals = intval($decimals); // number of digits after decimal
} else {
$format = $decimals; // format pattern for ICU only
}
if ($value === null) {
return $this->nullDisplay;
}
if (is_string($value)) {
$value = (float) $value;
}
// if (true === false){
if ($this->_intlLoaded){
$f = $this->createNumberFormatter(NumberFormatter::PERCENT, $format);
// $f->setAttribute(NumberFormatter::ROUNDING_MODE, NumberFormatter::ROUND_HALFUP);
$f->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
if ($decimals <= 5){
$f->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
}
if ($grouping === false){
$f->setAttribute(NumberFormatter::GROUPING_USED, false);
}
return $f->format($value);
} else {
$value = $value * 100;
$grouping = $grouping === true ? $this->thousandSeparator : '';
return number_format($value, $decimals, $this->decimalSeparator, $grouping) . ' %';
}
}
public function ufPercent($value){
if ($value === null){
return null;
}
return $this->unformatNumber($value) / 100;
}
/**
* Formats the value as a scientific number.
* @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 asScientific($value, $decimals = 4)
{
$format = null;
if(is_numeric($decimals)){
$decimals = intval($decimals); // number of digits after decimal
} else {
$format = $decimals; // format pattern for ICU only
}
if ($value === null) { if ($value === null) {
return $this->nullDisplay; return $this->nullDisplay;
} }
$ds = isset($this->decimalSeparator) ? $this->decimalSeparator : '.'; if (is_string($value)) {
$ts = isset($this->thousandSeparator) ? $this->thousandSeparator : ','; $value = (float) $value;
}
// if (true === false){
if ($this->_intlLoaded){
$f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $format);
$f->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
return $f->format($value);
} else {
return sprintf("%.{$decimals}E", $value);
}
return number_format((float) $value, $decimals, $ds, $ts);
} }
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.
* @return string the formatted result.
*/
public function asCurrency($value, $currency = null, $roundIncr = null, $grouping = true)
{
$format = null;
if ($value === null) {
return $this->nullDisplay;
}
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){
$currency = $this->currencyCode;
}
if ($roundIncr === null and $this->roundingIncrCurrency != null){
$roundIncr = $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);
}
if ($currency === null or trim($currency != '')){
return $f->format($value);
} else {
return $f->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';
}
}
$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. * Formats the value in bytes as a size in human readable form.
* @param integer $value value in bytes to be formatted * @param integer $value value in bytes to be formatted
...@@ -479,7 +1614,37 @@ class Formatter extends Component ...@@ -479,7 +1614,37 @@ class Formatter extends Component
return $verbose ? Yii::t('yii', '{n, plural, =1{# petabyte} other{# petabytes}}', $params) : Yii::t('yii', '{n} PB', $params); 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. * Formats the value as the time interval between a date and now in human readable form.
* *
...@@ -518,14 +1683,14 @@ class Formatter extends Component ...@@ -518,14 +1683,14 @@ class Formatter extends Component
$timezone = new \DateTimeZone($this->timeZone); $timezone = new \DateTimeZone($this->timeZone);
if ($referenceTime === null) { if ($referenceTime === null) {
$dateNow = new DateTime('now', $timezone); // $dateNow = new DateTime('now', $timezone);
} else { } else {
$referenceTime = $this->normalizeDatetimeValue($referenceTime); $referenceTime = $this->normalizeDatetimeValue($referenceTime);
$dateNow = new DateTime(null, $timezone); // $dateNow = new DateTime(null, $timezone);
$dateNow->setTimestamp($referenceTime); $dateNow->setTimestamp($referenceTime);
} }
$dateThen = new DateTime(null, $timezone); // $dateThen = new DateTime(null, $timezone);
$dateThen->setTimestamp($timestamp); $dateThen->setTimestamp($timestamp);
$interval = $dateThen->diff($dateNow); $interval = $dateThen->diff($dateNow);
...@@ -570,4 +1735,58 @@ class Formatter extends Component ...@@ -570,4 +1735,58 @@ class Formatter extends Component
return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s]); 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
* Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL
* ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE
* @param string $format the format to be used. Please refer to
* [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* @return NumberFormatter the created formatter instance
*/
protected function createNumberFormatter($type, $format)
{
$formatter = new NumberFormatter($this->locale, $type);
if ($format !== null) {
$formatter->setPattern($format);
}
if (!empty($this->numberFormatOptions)) {
foreach ($this->numberFormatOptions as $name => $attribute) {
$formatter->setAttribute($name, $attribute);
}
}
if (!empty($this->numberTextFormatOptions)) {
foreach ($this->numberTextFormatOptions as $name => $attribute) {
$formatter->setTextAttribute($name, $attribute);
}
}
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);
}
} }
<?php
namespace guggach\helpers;
/**
* International format definitions for decimal separator, thousand separator, dates,
* times and datetimes.
*
* Is only used if php extension isn't loaded. Otherwise the official ICU standard is
* used.
*
* Returns an array per local settings. Set the option 'language' => 'de-CH' in yii
* config file.
*
* Each language has xxx elements in their array like:
* [0] = decimal separator ('.')
* [1] = thousand separator (',')
* [2] = date short ('y-m-d')
* [3] = date medium ('Y-m-d')
* [4] = date long ('F j, Y')
* [5] = date full ('l, F j, Y')
* [6] = time short ('H:i')
* [7] = time medium ('H:i:s')
* [8] = time long ('g:i:sA')
* [9] = time full ('g:i:sA T')
* [10] = datetime short ('y-m-d H:i')
* [11] = datetime medium ('Y-m-d H:i:s')
* [12] = datetime long ('F j, Y g:i:sA')
* [13] = datetime full ('l, F j, Y g:i:sA T')
* [14] = currency code
*
* @author Erik Ruedin <e.ruedin@guggach.com>
* @version 0.1
*/
Class FormatDefs{
static function definition($local) {
$localDef = [
'en-US' =>
['.', ',', 'm/d/y', 'm/d/Y', 'F j, Y', 'l, F j, Y', 'H:i', 'H:i:s', 'g:i:sA', 'g:i:sA T', 'm/d/y H:i', 'm/d/Y H:i:s', 'F j, Y g:i:sA', 'l, F j, Y g:i:sA T', 'USD' ],
'de-CH' =>
['.', '\'', 'd.m.y', 'd.m.Y', 'j. F Y', 'l, j. F Y', 'H:i', 'H:i:s', 'G:i:s', 'G:i:s T', 'd.m.y H:i', 'd.m.Y H:i:s', 'F j, Y g:i:sA', 'l, F j, Y g:i:sA T', 'CHF' ],
'de-DE' =>
[',', '.', 'd.m.y', 'd.m.Y', 'j. F Y', 'l, j. F Y', 'H:i', 'H:i:s', 'G:i:s', 'G:i:s T', 'd.m.y H:i', 'd.m.Y H:i:s', 'F j, Y g:i:sA', 'l, F j, Y g:i:sA T', 'EUR' ],
];
if (isset($localDef[$local])){
return $localDef[$local];
} else{
return [];
}
}
}
...@@ -7,332 +7,22 @@ ...@@ -7,332 +7,22 @@
namespace yii\i18n; namespace yii\i18n;
use Yii;
use IntlDateFormatter;
use NumberFormatter;
use DateTime;
use yii\base\InvalidConfigException;
/** /**
* Formatter is the localized version of [[\yii\base\Formatter]]. * Dummy Formatter class in 'yii\i18n' for compatibility reason.
* Formatter class in 'yii\base' provides all functionality with localized format also
* independent if php extension "intl" is loaded or not.
* @see yii\base\Formatter.php
* *
* Formatter requires the PHP "intl" extension to be installed. Formatter supports localized * If php extension "intl" want to be used or can't be loaded then localized formats patterns
* formatting of date, time and numbers, based on the current [[locale]]. * could be entered in class 'yii\i18n\FormatDefs.php'
*
* This Formatter can replace the `formatter` application component that is configured by default.
* To do so, add the following to your application config under `components`:
*
* ```php
* 'formatter' => [
* 'class' => 'yii\i18n\Formatter',
* ]
* ``` * ```
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @author Enrica Ruedin <e.ruedin@guggach.com>
* @since 2.0 * @since 2.0
*/ */
class Formatter extends \yii\base\Formatter class Formatter extends \yii\base\Formatter
{ {
/**
* @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 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 $dateFormat = 'short';
/**
* @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 $timeFormat = 'short';
/**
* @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 $datetimeFormat = 'short';
/**
* @var array the options to be set for the NumberFormatter objects. Please refer to
* [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
* for the possible options. This property is used by [[createNumberFormatter]] when
* creating a new number formatter to format decimals, currencies, etc.
*/
public $numberFormatOptions = [];
/**
* @var string the character displayed as the decimal point when formatting a number.
* If not set, the decimal separator corresponding to [[locale]] will be used.
*/
public $decimalSeparator;
/**
* @var string the character displayed as the thousands separator character when formatting a number.
* If not set, the thousand separator corresponding to [[locale]] will be used.
*/
public $thousandSeparator;
/**
* @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;
/**
* Initializes the component.
* This method will check if the "intl" PHP extension is installed and set the
* default value of [[locale]].
* @throws InvalidConfigException if the "intl" PHP extension is not installed.
*/
public function init()
{
if (!extension_loaded('intl')) {
throw new InvalidConfigException('The "intl" PHP extension is not installed. It is required to format data values in localized formats.');
}
if ($this->locale === null) {
$this->locale = Yii::$app->language;
}
if ($this->decimalSeparator === null || $this->thousandSeparator === null || $this->currencyCode === null) {
$formatter = new NumberFormatter($this->locale, NumberFormatter::DECIMAL);
if ($this->decimalSeparator === null) {
$this->decimalSeparator = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
}
if ($this->thousandSeparator === null) {
$this->thousandSeparator = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
}
if ($this->currencyCode === null) {
$this->currencyCode = $formatter->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL);
}
}
parent::init();
}
private $_dateFormats = [
'short' => IntlDateFormatter::SHORT,
'medium' => IntlDateFormatter::MEDIUM,
'long' => IntlDateFormatter::LONG,
'full' => IntlDateFormatter::FULL,
];
/**
* 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()`
* - 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).
*
* @return string the formatted result
* @throws InvalidConfigException when formatting fails due to invalid parameters.
* @see dateFormat
*/
public function asDate($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
$value = $this->normalizeDatetimeValue($value);
if ($format === null) {
$format = $this->dateFormat;
}
if (isset($this->_dateFormats[$format])) {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($format);
}
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}
/**
* 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()`
* - 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).
*
* @return string the formatted result
* @throws InvalidConfigException when formatting fails due to invalid parameters.
* @see timeFormat
*/
public function asTime($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
$value = $this->normalizeDatetimeValue($value);
if ($format === null) {
$format = $this->timeFormat;
}
if (isset($this->_dateFormats[$format])) {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($format);
}
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}
/**
* 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
*
* @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).
*
* @return string the formatted result
* @throws InvalidConfigException when formatting fails due to invalid parameters.
* @see datetimeFormat
*/
public function asDatetime($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
$value = $this->normalizeDatetimeValue($value);
if ($format === null) {
$format = $this->datetimeFormat;
}
if (isset($this->_dateFormats[$format])) {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
} else {
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone);
if ($formatter !== null) {
$formatter->setPattern($format);
}
}
if ($formatter === null) {
throw new InvalidConfigException(intl_get_error_message());
}
return $formatter->format($value);
}
/**
* Formats the value as a decimal number.
* @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, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
return $this->createNumberFormatter(NumberFormatter::DECIMAL, $format)->format($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.
* If null, [[currencyCode]] will be used.
* @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 asCurrency($value, $currency = null, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
if ($currency === null){
$currency = $this->currencyCode;
}
return $this->createNumberFormatter(NumberFormatter::CURRENCY, $format)->formatCurrency($value, $currency);
}
/**
* Formats the value as a percent number.
* @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 asPercent($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
return $this->createNumberFormatter(NumberFormatter::PERCENT, $format)->format($value);
}
/**
* Formats the value as a scientific number.
* @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 asScientific($value, $format = null)
{
if ($value === null) {
return $this->nullDisplay;
}
return $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $format)->format($value);
}
/**
* Creates a number formatter based on the given type and format.
* @param integer $type the type of the number formatter
* @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* @return NumberFormatter the created formatter instance
*/
protected function createNumberFormatter($type, $format)
{
$formatter = new NumberFormatter($this->locale, $type);
if ($format !== null) {
$formatter->setPattern($format);
}
if (!empty($this->numberFormatOptions)) {
foreach ($this->numberFormatOptions as $name => $attribute) {
$formatter->setAttribute($name, $attribute);
}
}
return $formatter;
}
} }
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