Commit ef2f6a08 by Carsten Brandt

Merge pull request #5027 from yiisoft/date-format-convert

[WIP] extracted date format converting to a helper class
parents 01600bf6 3ff548a4
......@@ -32,7 +32,6 @@ $this->title = 'Yii Debugger';
if (isset($this->context->module->panels['db']) && isset($this->context->module->panels['request'])) {
echo " <h1>Available Debug Data</h1>";
$timeFormatter = extension_loaded('intl') ? Yii::createObject(['class' => 'yii\i18n\Formatter']) : Yii::$app->formatter;
$codes = [];
foreach ($manifest as $tag => $vals) {
......@@ -66,8 +65,8 @@ if (isset($this->context->module->panels['db']) && isset($this->context->module-
],
[
'attribute' => 'time',
'value' => function ($data) use ($timeFormatter) {
return '<span class="nowrap">' . $timeFormatter->asDateTime($data['time'], 'short') . '</span>';
'value' => function ($data) {
return '<span class="nowrap">' . Yii::$app->formatter->asDateTime($data['time'], 'short') . '</span>';
},
'format' => 'html',
],
......
......@@ -230,6 +230,7 @@ Yii Framework 2 Change Log
- Chg #2359: Refactored formatter class. One class with or without intl extension and PHP format pattern as standard (Erik_r, cebe)
- `yii\base\Formatter` functionality has been merged into `yii\i18n\Formatter`
- removed the `yii\base\Formatter` class
- Chg #1551: Refactored DateValidator to support ICU date format and uses the format defined in Formatter by default (cebe)
- Chg #2380: `yii\widgets\ActiveForm` will register validation js even if there are not fields inside (qiangxue)
- Chg #2898: `yii\console\controllers\AssetController` is now using hashes instead of timestamps (samdark)
- Chg #2913: RBAC `DbManager` is now initialized via migration (samdark)
......
......@@ -262,6 +262,14 @@ new ones save the following code as `convert.php` that should be placed in the s
The specification of the date and time formats is now using the ICU pattern format even if PHP intl extension is not installed.
You can prefix a date format with `php:` to use the old format of the PHP `date()`-function.
* The DateValidator has been refactored to use the same format as the Formatter class now (see previous change).
When you use the DateValidator and did not specify a format it will now be what is configured in the formatter class instead of 'Y-m-d'.
To get the old behavior of the DateValidator you have to set the format explicitly in your validation rule:
```php
['attributeName', 'date', 'format' => 'php:Y-m-d'],
```
* `beforeValidate()`, `beforeValidateAll()`, `afterValidate()`, `afterValidateAll()`, `ajaxBeforeSend()` and `ajaxComplete()`
are removed from `ActiveForm`. The same functionality is now achieved via JavaScript event mechanism like the following:
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\helpers;
use IntlDateFormatter;
use Yii;
/**
* BaseFormatConverter provides concrete implementation for [[FormatConverter]].
*
* Do not use BaseFormatConverter. Use [[FormatConverter]] instead.
*
* @author Carsten Brandt <mail@cebe.cc>
* @author Enrica Ruedin <e.ruedin@guggach.com>
* @since 2.0
*/
class BaseFormatConverter
{
/**
* @var array the php fallback definition to use for the ICU short patterns `short`, `medium`, `long` and `full`.
* This is used as fallback when the intl extension is not installed.
*/
public static $phpFallbackDatePatterns = [
'short' => [
'date' => 'n/j/y',
'time' => 'H:i',
'datetime' => 'n/j/y H:i',
],
'medium' => [
'date' => 'M j, Y',
'time' => 'g:i:s A',
'datetime' => 'M j, Y g:i:s A',
],
'long' => [
'date' => 'F j, Y',
'time' => 'g:i:sA',
'datetime' => 'F j, Y g:i:sA',
],
'full' => [
'date' => 'l, F j, Y',
'time' => 'g:i:sA T',
'datetime' => 'l, F j, Y g:i:sA T',
],
];
/**
* @var array the jQuery UI fallback definition to use for the ICU short patterns `short`, `medium`, `long` and `full`.
* This is used as fallback when the intl extension is not installed.
*/
public static $juiFallbackDatePatterns = [
'short' => [
'date' => 'd/m/y',
'time' => '',
'datetime' => 'd/m/y',
],
'medium' => [
'date' => 'M d, yy',
'time' => '',
'datetime' => 'M d, yy',
],
'long' => [
'date' => 'MM d, yy',
'time' => '',
'datetime' => 'MM d, yy',
],
'full' => [
'date' => 'DD, MM d, yy',
'time' => '',
'datetime' => 'DD, MM d, yy',
],
];
private static $_icuShortFormats = [
'short' => 3, // IntlDateFormatter::SHORT,
'medium' => 2, // IntlDateFormatter::MEDIUM,
'long' => 1, // IntlDateFormatter::LONG,
'full' => 0, // IntlDateFormatter::FULL,
];
/**
* Converts a date format pattern from [ICU format][] to [php date() function format][].
*
* The conversion is limited to date patterns that do not use escaped characters.
* Patterns like `d 'of' MMMM yyyy` which will result in a date like `1 of December 2014` may not be converted correctly
* because of the use of escaped characters.
*
* Pattern constructs that are not supported by the PHP format will be removed.
*
* [php date() function format]: http://php.net/manual/en/function.date.php
* [ICU format]: http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax
*
* @param string $pattern date format pattern in ICU format.
* @param string $type 'date', 'time', or 'datetime'.
* @param string $locale the locale to use for converting ICU short patterns `short`, `medium`, `long` and `full`.
* If not given, `Yii::$app->language` will be used.
* @return string The converted date format pattern.
*/
public static function convertDateIcuToPhp($pattern, $type = 'date', $locale = null)
{
if (isset(self::$_icuShortFormats[$pattern])) {
if (extension_loaded('intl')) {
if ($locale === null) {
$locale = Yii::$app->language;
}
if ($type === 'date') {
$formatter = new IntlDateFormatter($locale, self::$_icuShortFormats[$pattern], IntlDateFormatter::NONE);
} elseif ($type === 'time') {
$formatter = new IntlDateFormatter($locale, IntlDateFormatter::NONE, self::$_icuShortFormats[$pattern]);
} else {
$formatter = new IntlDateFormatter($locale, self::$_icuShortFormats[$pattern], self::$_icuShortFormats[$pattern]);
}
$pattern = $formatter->getPattern();
} else {
return static::$phpFallbackDatePatterns[$pattern][$type];
}
}
// http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax
return strtr($pattern, [
'G' => '', // era designator like (Anno Domini)
'Y' => 'o', // 4digit year of "Week of Year"
'y' => 'Y', // 4digit year e.g. 2014
'yyyy' => 'Y', // 4digit year e.g. 2014
'yy' => 'y', // 2digit year number eg. 14
'u' => '', // extended year e.g. 4601
'U' => '', // cyclic year name, as in Chinese lunar calendar
'r' => '', // related Gregorian year e.g. 1996
'Q' => '', // number of quarter
'QQ' => '', // number of quarter '02'
'QQQ' => '', // quarter 'Q2'
'QQQQ' => '', // quarter '2nd quarter'
'QQQQQ' => '', // number of quarter '2'
'q' => '', // number of Stand Alone quarter
'qq' => '', // number of Stand Alone quarter '02'
'qqq' => '', // Stand Alone quarter 'Q2'
'qqqq' => '', // Stand Alone quarter '2nd quarter'
'qqqqq' => '', // number of Stand Alone quarter '2'
'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
'MMMMM' => '', //
'L' => 'm', // Stand alone month in year
'LL' => 'm', // Stand alone month in year
'LLL' => 'M', // Stand alone month in year
'LLLL' => 'F', // Stand alone month in year
'LLLLL' => '', // Stand alone month in year
'w' => 'W', // ISO-8601 week number of year
'ww' => 'W', // ISO-8601 week number of year
'W' => '', // week of the current month
'd' => 'j', // day without leading zeros
'dd' => 'd', // day with leading zeros
'D' => 'z', // day of the year 0 to 365
'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.
'E' => 'D', // day of week written in short form eg. Sun
'EE' => 'D',
'EEE' => 'D',
'EEEE' => 'l', // day of week fully written eg. Sunday
'EEEEE' => '',
'EEEEEE' => '',
'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
'eee' => 'D',
'eeee' => 'l',
'eeeee' => '',
'eeeeee' => '',
'c' => 'N', // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
'cc' => 'N', // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
'ccc' => 'D',
'cccc' => 'l',
'ccccc' => '',
'cccccc' => '',
'a' => 'a', // am/pm marker
'h' => 'g', // 12-hour format of an hour without leading zeros 1 to 12h
'hh' => 'h', // 12-hour format of an hour with leading zeros, 01 to 12 h
'H' => 'G', // 24-hour format of an hour without leading zeros 0 to 23h
'HH' => 'H', // 24-hour format of an hour with leading zeros, 00 to 23 h
'k' => '', // hour in day (1~24)
'kk' => '', // hour in day (1~24)
'K' => '', // hour in am/pm (0~11)
'KK' => '', // hour in am/pm (0~11)
'm' => 'i', // Minutes without leading zeros, not supported by php but we fallback
'mm' => 'i', // Minutes with leading zeros
's' => 's', // Seconds, without leading zeros, not supported by php but we fallback
'ss' => 's', // Seconds, with leading zeros
'S' => '', // fractional second
'SS' => '', // fractional second
'SSS' => '', // fractional second
'SSSS' => '', // fractional second
'A' => '', // milliseconds in day
'z' => 'T', // Timezone abbreviation
'zz' => 'T', // Timezone abbreviation
'zzz' => 'T', // Timezone abbreviation
'zzzz' => 'T', // Timzone full name, not supported by php but we fallback
'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
'ZZZZ' => '\G\M\TP', // Time Zone: long localized GMT (=OOOO) e.g. GMT-08:00
'ZZZZZ' => '', // TIme Zone: ISO8601 extended hms? (=XXXXX)
'O' => '', // Time Zone: short localized GMT e.g. GMT-8
'OOOO' => '\G\M\TP', // Time Zone: long localized GMT (=ZZZZ) e.g. GMT-08:00
'v' => '\G\M\TP', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here
'vvvv' => '\G\M\TP', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here
'V' => '', // Time Zone: short time zone ID
'VV' => 'e', // Time Zone: long time zone ID
'VVV' => '', // Time Zone: time zone exemplar city
'VVVV' => '\G\M\TP', // Time Zone: generic location (falls back to OOOO) using the ICU defined fallback here
'X' => '', // Time Zone: ISO8601 basic hm?, with Z for 0, e.g. -08, +0530, Z
'XX' => 'O, \Z', // Time Zone: ISO8601 basic hm, with Z, e.g. -0800, Z
'XXX' => 'P, \Z', // Time Zone: ISO8601 extended hm, with Z, e.g. -08:00, Z
'XXXX' => '', // Time Zone: ISO8601 basic hms?, with Z, e.g. -0800, -075258, Z
'XXXXX' => '', // Time Zone: ISO8601 extended hms?, with Z, e.g. -08:00, -07:52:58, Z
'x' => '', // Time Zone: ISO8601 basic hm?, without Z for 0, e.g. -08, +0530
'xx' => 'O', // Time Zone: ISO8601 basic hm, without Z, e.g. -0800
'xxx' => 'P', // Time Zone: ISO8601 extended hm, without Z, e.g. -08:00
'xxxx' => '', // Time Zone: ISO8601 basic hms?, without Z, e.g. -0800, -075258
'xxxxx' => '', // Time Zone: ISO8601 extended hms?, without Z, e.g. -08:00, -07:52:58
]);
}
/**
* Converts a date format pattern from [php date() function format][] to [ICU format][].
*
* The conversion is limited to date patterns that do not use escaped characters.
* Patterns like `jS \o\f F Y` which will result in a date like `1st of December 2014` may not be converted correctly
* because of the use of escaped characters.
*
* Pattern constructs that are not supported by the ICU format will be removed.
*
* [php date() function format]: http://php.net/manual/en/function.date.php
* [ICU format]: http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax
*
* @param string $pattern date format pattern in php date()-function format.
* @return string The converted date format pattern.
*/
public static function convertDatePhpToIcu($pattern)
{
// http://php.net/manual/en/function.date.php
return strtr($pattern, [
// Day
'd' => 'dd', // Day of the month, 2 digits with leading zeros 01 to 31
'D' => 'eee', // A textual representation of a day, three letters Mon through Sun
'j' => 'd', // Day of the month without leading zeros 1 to 31
'l' => 'eeee', // A full textual representation of the day of the week Sunday through Saturday
'N' => 'e', // ISO-8601 numeric representation of the day of the week, 1 (for Monday) through 7 (for Sunday)
'S' => '', // English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
'w' => '', // Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
'z' => 'D', // The day of the year (starting from 0) 0 through 365
// Week
'W' => 'w', // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
// Month
'F' => 'MMMM', // A full textual representation of a month, January through December
'm' => 'MM', // Numeric representation of a month, with leading zeros 01 through 12
'M' => 'MMM', // A short textual representation of a month, three letters Jan through Dec
'n' => 'M', // Numeric representation of a month, without leading zeros 1 through 12, not supported by ICU but we fallback to "with leading zero"
't' => '', // Number of days in the given month 28 through 31
// Year
'L' => '', // Whether it's a leap year, 1 if it is a leap year, 0 otherwise.
'o' => 'Y', // 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.
'Y' => 'yyyy', // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
'y' => 'yy', // A two digit representation of a year Examples: 99 or 03
// Time
'a' => 'a', // Lowercase Ante meridiem and Post meridiem, am or pm
'A' => 'a', // Uppercase Ante meridiem and Post meridiem, AM or PM, not supported by ICU but we fallback to lowercase
'B' => '', // Swatch Internet time 000 through 999
'g' => 'h', // 12-hour format of an hour without leading zeros 1 through 12
'G' => 'H', // 24-hour format of an hour without leading zeros 0 to 23h
'h' => 'hh', // 12-hour format of an hour with leading zeros, 01 to 12 h
'H' => 'HH', // 24-hour format of an hour with leading zeros, 00 to 23 h
'i' => 'mm', // Minutes with leading zeros 00 to 59
's' => 'ss', // Seconds, with leading zeros 00 through 59
'u' => '', // Microseconds. Example: 654321
// Timezone
'e' => 'VV', // Timezone identifier. Examples: UTC, GMT, Atlantic/Azores
'I' => '', // Whether or not the date is in daylight saving time, 1 if Daylight Saving Time, 0 otherwise.
'O' => 'xx', // Difference to Greenwich time (GMT) in hours, Example: +0200
'P' => 'xxx', // Difference to Greenwich time (GMT) with colon between hours and minutes, Example: +02:00
'T' => 'zzz', // Timezone abbreviation, Examples: EST, MDT ...
'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
// Full Date/Time
'c' => 'yyyy-MM-dd\'T\'HH:mm:ssxxx', // ISO 8601 date, e.g. 2004-02-12T15:19:21+00:00
'r' => 'eee, dd MMM yyyy HH:mm:ss xx', // RFC 2822 formatted date, Example: Thu, 21 Dec 2000 16:01:07 +0200
'U' => '', // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
]);
}
/**
* Converts a date format pattern from [ICU format][] to [jQuery UI date format][].
*
* Pattern constructs that are not supported by the jQuery UI format will be removed.
*
* [jQuery UI date format]: http://api.jqueryui.com/datepicker/#utility-formatDate
* [ICU format]: http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax
*
* @param string $pattern date format pattern in ICU format.
* @param string $type 'date', 'time', or 'datetime'.
* @param string $locale the locale to use for converting ICU short patterns `short`, `medium`, `long` and `full`.
* If not given, `Yii::$app->language` will be used.
* @return string The converted date format pattern.
*/
public static function convertDateIcuToJui($pattern, $type = 'date', $locale = null)
{
if (isset(self::$_icuShortFormats[$pattern])) {
if (extension_loaded('intl')) {
if ($locale === null) {
$locale = Yii::$app->language;
}
if ($type === 'date') {
$formatter = new IntlDateFormatter($locale, self::$_icuShortFormats[$pattern], IntlDateFormatter::NONE);
} elseif ($type === 'time') {
$formatter = new IntlDateFormatter($locale, IntlDateFormatter::NONE, self::$_icuShortFormats[$pattern]);
} else {
$formatter = new IntlDateFormatter($locale, self::$_icuShortFormats[$pattern], self::$_icuShortFormats[$pattern]);
}
$pattern = $formatter->getPattern();
} else {
return static::$juiFallbackDatePatterns[$pattern][$type];
}
}
// http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax
return strtr($pattern, [
'G' => '', // era designator like (Anno Domini)
'Y' => '', // 4digit year of "Week of Year"
'y' => 'yy', // 4digit year e.g. 2014
'yyyy' => 'yy', // 4digit year e.g. 2014
'yy' => 'y', // 2digit year number eg. 14
'u' => '', // extended year e.g. 4601
'U' => '', // cyclic year name, as in Chinese lunar calendar
'r' => '', // related Gregorian year e.g. 1996
'Q' => '', // number of quarter
'QQ' => '', // number of quarter '02'
'QQQ' => '', // quarter 'Q2'
'QQQQ' => '', // quarter '2nd quarter'
'QQQQQ' => '', // number of quarter '2'
'q' => '', // number of Stand Alone quarter
'qq' => '', // number of Stand Alone quarter '02'
'qqq' => '', // Stand Alone quarter 'Q2'
'qqqq' => '', // Stand Alone quarter '2nd quarter'
'qqqqq' => '', // number of Stand Alone quarter '2'
'M' => 'm', // Numeric representation of a month, without leading zeros
'MM' => 'mm', // Numeric representation of a month, with leading zeros
'MMM' => 'M', // A short textual representation of a month, three letters
'MMMM' => 'MM', // A full textual representation of a month, such as January or March
'MMMMM' => '', //
'L' => 'mm', // Stand alone month in year
'LL' => 'mm', // Stand alone month in year
'LLL' => 'M', // Stand alone month in year
'LLLL' => 'MM', // Stand alone month in year
'LLLLL' => '', // Stand alone month in year
'w' => '', // ISO-8601 week number of year
'ww' => '', // ISO-8601 week number of year
'W' => '', // week of the current month
'd' => 'd', // day without leading zeros
'dd' => 'dd', // day with leading zeros
'D' => 'o', // day of the year 0 to 365
'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.
'E' => 'D', // day of week written in short form eg. Sun
'EE' => 'D',
'EEE' => 'D',
'EEEE' => 'DD', // day of week fully written eg. Sunday
'EEEEE' => '',
'EEEEEE' => '',
'e' => '', // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
'ee' => '', // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
'eee' => 'D',
'eeee' => '',
'eeeee' => '',
'eeeeee' => '',
'c' => '', // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
'cc' => '', // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
'ccc' => 'D',
'cccc' => 'DD',
'ccccc' => '',
'cccccc' => '',
'a' => '', // am/pm marker
'h' => '', // 12-hour format of an hour without leading zeros 1 to 12h
'hh' => '', // 12-hour format of an hour with leading zeros, 01 to 12 h
'H' => '', // 24-hour format of an hour without leading zeros 0 to 23h
'HH' => '', // 24-hour format of an hour with leading zeros, 00 to 23 h
'k' => '', // hour in day (1~24)
'kk' => '', // hour in day (1~24)
'K' => '', // hour in am/pm (0~11)
'KK' => '', // hour in am/pm (0~11)
'm' => '', // Minutes without leading zeros, not supported by php but we fallback
'mm' => '', // Minutes with leading zeros
's' => '', // Seconds, without leading zeros, not supported by php but we fallback
'ss' => '', // Seconds, with leading zeros
'S' => '', // fractional second
'SS' => '', // fractional second
'SSS' => '', // fractional second
'SSSS' => '', // fractional second
'A' => '', // milliseconds in day
'z' => '', // Timezone abbreviation
'zz' => '', // Timezone abbreviation
'zzz' => '', // Timezone abbreviation
'zzzz' => '', // Timzone full name, not supported by php but we fallback
'Z' => '', // Difference to Greenwich time (GMT) in hours
'ZZ' => '', // Difference to Greenwich time (GMT) in hours
'ZZZ' => '', // Difference to Greenwich time (GMT) in hours
'ZZZZ' => '', // Time Zone: long localized GMT (=OOOO) e.g. GMT-08:00
'ZZZZZ' => '', // TIme Zone: ISO8601 extended hms? (=XXXXX)
'O' => '', // Time Zone: short localized GMT e.g. GMT-8
'OOOO' => '', // Time Zone: long localized GMT (=ZZZZ) e.g. GMT-08:00
'v' => '', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here
'vvvv' => '', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here
'V' => '', // Time Zone: short time zone ID
'VV' => '', // Time Zone: long time zone ID
'VVV' => '', // Time Zone: time zone exemplar city
'VVVV' => '', // Time Zone: generic location (falls back to OOOO) using the ICU defined fallback here
'X' => '', // Time Zone: ISO8601 basic hm?, with Z for 0, e.g. -08, +0530, Z
'XX' => '', // Time Zone: ISO8601 basic hm, with Z, e.g. -0800, Z
'XXX' => '', // Time Zone: ISO8601 extended hm, with Z, e.g. -08:00, Z
'XXXX' => '', // Time Zone: ISO8601 basic hms?, with Z, e.g. -0800, -075258, Z
'XXXXX' => '', // Time Zone: ISO8601 extended hms?, with Z, e.g. -08:00, -07:52:58, Z
'x' => '', // Time Zone: ISO8601 basic hm?, without Z for 0, e.g. -08, +0530
'xx' => '', // Time Zone: ISO8601 basic hm, without Z, e.g. -0800
'xxx' => '', // Time Zone: ISO8601 extended hm, without Z, e.g. -08:00
'xxxx' => '', // Time Zone: ISO8601 basic hms?, without Z, e.g. -0800, -075258
'xxxxx' => '', // Time Zone: ISO8601 extended hms?, without Z, e.g. -08:00, -07:52:58
]);
}
/**
* Converts a date format pattern from [php date() function format][] to [jQuery UI date format][].
*
* The conversion is limited to date patterns that do not use escaped characters.
* Patterns like `jS \o\f F Y` which will result in a date like `1st of December 2014` may not be converted correctly
* because of the use of escaped characters.
*
* Pattern constructs that are not supported by the jQuery UI format will be removed.
*
* [php date() function format]: http://php.net/manual/en/function.date.php
* [jQuery UI date format]: http://api.jqueryui.com/datepicker/#utility-formatDate
*
* @param string $pattern date format pattern in php date()-function format.
* @return string The converted date format pattern.
*/
public static function convertDatePhpToJui($pattern)
{
// http://php.net/manual/en/function.date.php
return strtr($pattern, [
// Day
'd' => 'dd', // Day of the month, 2 digits with leading zeros 01 to 31
'D' => 'D', // A textual representation of a day, three letters Mon through Sun
'j' => 'd', // Day of the month without leading zeros 1 to 31
'l' => 'DD', // A full textual representation of the day of the week Sunday through Saturday
'N' => '', // ISO-8601 numeric representation of the day of the week, 1 (for Monday) through 7 (for Sunday)
'S' => '', // English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
'w' => '', // Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
'z' => 'o', // The day of the year (starting from 0) 0 through 365
// Week
'W' => '', // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
// Month
'F' => 'MM', // A full textual representation of a month, January through December
'm' => 'mm', // Numeric representation of a month, with leading zeros 01 through 12
'M' => 'M', // A short textual representation of a month, three letters Jan through Dec
'n' => 'm', // Numeric representation of a month, without leading zeros 1 through 12
't' => '', // Number of days in the given month 28 through 31
// Year
'L' => '', // Whether it's a leap year, 1 if it is a leap year, 0 otherwise.
'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.
'Y' => 'yy', // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
'y' => 'y', // A two digit representation of a year Examples: 99 or 03
// Time
'a' => '', // Lowercase Ante meridiem and Post meridiem, am or pm
'A' => '', // Uppercase Ante meridiem and Post meridiem, AM or PM, not supported by ICU but we fallback to lowercase
'B' => '', // Swatch Internet time 000 through 999
'g' => '', // 12-hour format of an hour without leading zeros 1 through 12
'G' => '', // 24-hour format of an hour without leading zeros 0 to 23h
'h' => '', // 12-hour format of an hour with leading zeros, 01 to 12 h
'H' => '', // 24-hour format of an hour with leading zeros, 00 to 23 h
'i' => '', // Minutes with leading zeros 00 to 59
's' => '', // Seconds, with leading zeros 00 through 59
'u' => '', // Microseconds. Example: 654321
// Timezone
'e' => '', // Timezone identifier. Examples: UTC, GMT, Atlantic/Azores
'I' => '', // Whether or not the date is in daylight saving time, 1 if Daylight Saving Time, 0 otherwise.
'O' => '', // Difference to Greenwich time (GMT) in hours, Example: +0200
'P' => '', // Difference to Greenwich time (GMT) with colon between hours and minutes, Example: +02:00
'T' => '', // Timezone abbreviation, Examples: EST, MDT ...
'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
// Full Date/Time
'c' => 'yyyy-MM-dd', // ISO 8601 date, e.g. 2004-02-12T15:19:21+00:00, skipping the time here because it is not supported
'r' => 'D, d M yy', // RFC 2822 formatted date, Example: Thu, 21 Dec 2000 16:01:07 +0200, skipping the time here because it is not supported
'U' => '@', // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
]);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\helpers;
/**
* FormatConverter provides functionality to convert between different formatting pattern formats.
*
* It provides functions to convert date format patterns between different conventions.
*
* @author Carsten Brandt <mail@cebe.cc>
* @author Enrica Ruedin <e.ruedin@guggach.com>
* @since 2.0
*/
class FormatConverter extends BaseFormatConverter
{
}
......@@ -15,6 +15,7 @@ use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\helpers\FormatConverter;
use yii\helpers\HtmlPurifier;
use yii\helpers\Html;
......@@ -72,28 +73,49 @@ class Formatter extends Component
* @var string the default format string to be used to format a [[asDate()|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).
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
* Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
* PHP [date()](http://php.net/manual/de/function.date.php)-function.
*
* For example:
*
* ```php
* 'MM/dd/yyyy' // date in ICU format
* 'php:m/d/Y' // the same date in PHP format
* ```
*/
public $dateFormat = 'medium';
/**
* @var string the default format string to be used to format a [[asTime()|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).
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
* Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
* PHP [date()](http://php.net/manual/de/function.date.php)-function.
*
* For example:
*
* ```php
* 'HH:mm:ss' // time in ICU format
* 'php:H:i:s' // the same time in PHP format
* ```
*/
public $timeFormat = 'medium';
/**
* @var string the default format string to be used to format a [[asDateTime()|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).
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
*
* Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
* PHP [date()](http://php.net/manual/de/function.date.php)-function.
*
* For example:
*
* ```php
* 'MM/dd/yyyy HH:mm:ss' // date and time in ICU format
* 'php:m/d/Y H:i:s' // the same date and time in PHP format
* ```
*/
public $datetimeFormat = 'medium';
/**
......@@ -464,34 +486,6 @@ class Formatter extends Component
];
/**
* @var array with the standard php definition for short, medium, long an full
* format as pattern for date, time and datetime.
* This is used as fallback when the intl extension is not installed.
*/
private $_phpNameToPattern = [
'short' => [
'date' => 'n/j/y',
'time' => 'H:i',
'datetime' => 'n/j/y H:i',
],
'medium' => [
'date' => 'M j, Y',
'time' => 'g:i:s A',
'datetime' => 'M j, Y g:i:s A',
],
'long' => [
'date' => 'F j, Y',
'time' => 'g:i:sA',
'datetime' => 'F j, Y g:i:sA',
],
'full' => [
'date' => 'l, F j, Y',
'time' => 'g:i:sA T',
'datetime' => 'l, F j, Y g:i:sA T',
],
];
/**
* @param integer $value normalized datetime value
* @param string $format the format used to convert the value into a date string.
* @param string $type 'date', 'time', or 'datetime'.
......@@ -506,7 +500,9 @@ class Formatter extends Component
}
if ($this->_intlLoaded) {
$format = $this->getIntlDatePattern($format);
if (strncmp($format, 'php:', 4) === 0) {
$format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
}
if (isset($this->_dateFormats[$format])) {
if ($type === 'date') {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
......@@ -523,11 +519,10 @@ class Formatter extends Component
}
return $formatter->format($value);
} else {
// replace short, medium, long and full with real patterns in case intl is not loaded.
if (isset($this->_phpNameToPattern[$format][$type])) {
$format = $this->_phpNameToPattern[$format][$type];
if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4);
} else {
$format = $this->getPhpDatePattern($format);
$format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
}
$date = new DateTime(null, new \DateTimeZone($this->timeZone));
$date->setTimestamp($value);
......@@ -561,170 +556,6 @@ class Formatter extends Component
}
}
private function getIntlDatePattern($pattern)
{
if (strpos($pattern, 'php:') === 0) {
return $this->convertPatternPhpToIcu(substr($pattern, 4));
} else {
return $pattern;
}
}
private function getPhpDatePattern($pattern)
{
if (strpos($pattern, 'php:') === 0) {
return substr($pattern, 4);
} else {
return $this->convertPatternIcuToPhp($pattern);
}
}
/**
* intlFormatter class (ICU based) and DateTime class don't have same format string.
* These format patterns are completely incompatible and must be converted.
*
* This method converts an ICU (php intl) formatted date, time or datetime string in
* a php compatible format string.
*
* @param string $pattern dateformat pattern like 'dd.mm.yyyy' or 'short'/'medium'/
* 'long'/'full' or 'db
* @return string with converted date format pattern.
* @throws InvalidConfigException
*/
private function convertPatternIcuToPhp($pattern)
{
return strtr($pattern, [
'dd' => 'd', // day with leading zeros
'd' => 'j', // day without leading zeros
'E' => 'D', // day written in short form eg. Sun
'EE' => 'D',
'EEE' => 'D',
'EEEE' => 'l', // day fully written eg. Sunday
'e' => 'N', // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
'ee' => 'N', // php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
// engl. ordinal st, nd, rd; it's not support by ICU but we added
'D' => 'z', // day of the year 0 to 365
'w' => 'W', // ISO-8601 week number of year, weeks starting on Monday
'W' => '', // week of the current month; isn't supported by php
'F' => '', // Day of Week in Month. eg. 2nd Wednesday in July
'g' => '', // Modified Julian day. This is different from the conventional Julian day number in two regards.
'M' => 'n', // Numeric representation of a month, without leading zeros
'MM' => 'm', // Numeric representation of a month, with leading zeros
'MMM' => 'M', // A short textual representation of a month, three letters
'MMMM' => 'F', // A full textual representation of a month, such as January or March
'Q' => '', // number of quarter not supported in php
'QQ' => '', // number of quarter '02' not supported in php
'QQQ' => '', // quarter 'Q2' not supported in php
'QQQQ' => '', // quarter '2nd quarter' not supported in php
'QQQQQ' => '', // number of quarter '2' not supported in php
'Y' => 'Y', // 4digit year number eg. 2014
'y' => 'Y', // 4digit year also
'yyyy' => 'Y', // 4digit year also
'yy' => 'y', // 2digit year number eg. 14
'r' => '', // related Gregorian year, not supported by php
'G' => '', // ear designator like AD
'a' => 'a', // Lowercase Ante meridiem and Post
'h' => 'g', // 12-hour format of an hour without leading zeros 1 to 12h
'K' => 'g', // 12-hour format of an hour without leading zeros 0 to 11h, not supported by php
'H' => 'G', // 24-hour format of an hour without leading zeros 0 to 23h
'k' => 'G', // 24-hour format of an hour without leading zeros 1 to 24h, not supported by php
'hh' => 'h', // 12-hour format of an hour with leading zeros, 01 to 12 h
'KK' => 'h', // 12-hour format of an hour with leading zeros, 00 to 11 h, not supported by php
'HH' => 'H', // 24-hour format of an hour with leading zeros, 00 to 23 h
'kk' => 'H', // 24-hour format of an hour with leading zeros, 01 to 24 h, not supported by php
'm' => 'i', // Minutes without leading zeros, not supported by php
'mm' => 'i', // Minutes with leading zeros
's' => 's', // Seconds, without leading zeros, not supported by php
'ss' => 's', // Seconds, with leading zeros
'SSS' => '', // millisecond (maximum of 3 significant digits), not supported by php
'A' => '', // milliseconds in day, not supported by php
'Z' => 'O', // Difference to Greenwich time (GMT) in hours
'ZZ' => 'O', // Difference to Greenwich time (GMT) in hours
'ZZZ' => 'O', // Difference to Greenwich time (GMT) in hours
'z' => 'T', // Timezone abbreviation
'zz' => 'T', // Timezone abbreviation
'zzz' => 'T', // Timezone abbreviation
'zzzz' => 'T', // Timzone full name, not supported by php
'V' => 'e', // Timezone identifier eg. Europe/Berlin
'VV' => 'e',
'VVV' => 'e',
'VVVV' => 'e'
]);
}
/**
* intlFormatter class (ICU based) and DateTime class don't have same format string.
* These format patterns are completely incompatible and must be converted.
*
* This method converts PHP formatted date, time or datetime string in
* an ICU (php intl) compatible format string.
*
* @param string $pattern dateformat pattern like 'd.m.Y' or 'short'/'medium'/
* 'long'/'full' or 'db
* @return string with converted date format pattern.
* @throws InvalidConfigException
*/
private function convertPatternPhpToIcu($pattern)
{
return strtr($pattern, [
'd' => 'dd', // day with leading zeros
'j' => 'd', // day without leading zeros
'D' => 'EEE', // day written in short form eg. Sun
'l' => 'EEEE', // day fully written eg. Sunday
'N' => 'e', // ISO-8601 numeric representation of the day of the week 1=Mon to 7=Sun
// php 'w' 0=Sun to 6=Sat isn't supported by ICU -> 'w' means week number of year
'S' => '', // engl. ordinal st, nd, rd; it's not support by ICU
'z' => 'D', // day of the year 0 to 365
'W' => 'w', // ISO-8601 week number of year, weeks starting on Monday
// week of the current month; isn't supported by php
// Day of Week in Month. eg. 2nd Wednesday in July not supported by php
// Modified Julian day. This is different from the conventional Julian day number in two regards.
'n'=> 'M', // Numeric representation of a month, without leading zeros
'm' => 'MM', // Numeric representation of a month, with leading zeros
'M' => 'MMM', // A short textual representation of a month, three letters
'F' => 'MMMM', // A full textual representation of a month, such as January or March
// number of quarter not supported in php
// number of quarter '02' not supported in php
// quarter 'Q2' not supported in php
// quarter '2nd quarter' not supported in php
// number of quarter '2' not supported in php
'Y' => 'yyyy', // 4digit year eg. 2014
'y' => 'yy', // 2digit year number eg. 14
// related Gregorian year, not supported by php
// ear designator like AD
'a' => 'a', // Lowercase Ante meridiem and Post am. or pm.
'A' => 'a', // Upercase Ante meridiem and Post AM or PM, not supported by ICU
'g' => 'h', // 12-hour format of an hour without leading zeros 1 to 12h
// 12-hour format of an hour without leading zeros 0 to 11h, not supported by php
'G' => 'H', // 24-hour format of an hour without leading zeros 0 to 23h
// 24-hour format of an hour without leading zeros 1 to 24h, not supported by php
'h' => 'hh', // 12-hour format of an hour with leading zeros, 01 to 12 h
// 12-hour format of an hour with leading zeros, 00 to 11 h, not supported by php
'H' => 'HH', // 24-hour format of an hour with leading zeros, 00 to 23 h
// 24-hour format of an hour with leading zeros, 01 to 24 h, not supported by php
// Minutes without leading zeros, not supported by php
'i' => 'mm', // Minutes with leading zeros
// Seconds, without leading zeros, not supported by php
's' => 'ss', // Seconds, with leading zeros
// millisecond (maximum of 3 significant digits), not supported by php
// milliseconds in day, not supported by php
'O' => 'Z', // Difference to Greenwich time (GMT) in hours
'T' => 'z', // Timezone abbreviation
// Timzone full name, not supported by php
'e' => 'VV', // Timezone identifier eg. Europe/Berlin
'w' => '', // Numeric representation of the day of the week 0=Sun, 6=Sat, not sup. ICU
'L' => '', //Whether it's a leap year 1= leap, 0= normal year, not sup. ICU
'B' => '', // Swatch Internet time, 000 to 999, not sup. ICU
'u' => '', // Microseconds Note that date() will always generate 000000 since it takes an integer parameter, not sup. ICU
'P' => '', // Difference to Greenwich time (GMT) with colon between hours and minutes, not sup. ICU
'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive, not sup. ICU
'c' => 'yyy-MM-dd\'T\'mm:HH:ssZ', //ISO 8601 date, it works only if nothing else than 'c' is in pattern.
'r' => 'eee, dd MMM yyyy mm:HH:ss Z', // » RFC 2822 formatted date, it works only if nothing else than 'r' is in pattern
'U' => '' // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), not supported in ICU
]);
}
/**
* Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
* @param integer|string|DateTime|\DateInterval $value the value to be formatted. The following
......@@ -814,7 +645,9 @@ class Formatter extends Component
if ($interval->i >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->locale);
}
if ($interval->s == 0) {
return Yii::t('yii', 'just now', [], $this->locale);
}
return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
} else {
if ($interval->y >= 1) {
......@@ -832,7 +665,9 @@ class Formatter extends Component
if ($interval->i >= 1) {
return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->locale);
}
if ($interval->s == 0) {
return Yii::t('yii', 'just now', [], $this->locale);
}
return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
}
}
......
......@@ -7,7 +7,7 @@ return [
'messagePath' => __DIR__,
// array, required, list of language codes that the extracted messages
// should be translated to. For example, ['zh-CN', 'de'].
'languages' => ['ar', 'bg', 'ca', 'da', 'de', 'el', 'es', 'et', 'fa-IR', 'fi', 'fr', 'hu', 'id', 'it', 'ja', 'kk', 'ko', 'lt', 'lv', 'nl', 'pl', 'pt-BR', 'pt-PT', 'ro', 'ru', 'sk', 'sr', 'sr-Latn', 'th', 'uk', 'vi', 'zh-CN','zh-TW'],
'languages' => ['ar', 'bg', 'ca', 'da', 'de', 'el', 'es', 'et', 'fa-IR', 'fi', 'fr', 'hu', 'id', 'it', 'ja', 'kk', 'ko', 'lt', 'lv', 'nl', 'pl', 'pt', 'pt-BR', 'ro', 'ru', 'sk', 'sr', 'sr-Latn', 'th', 'uk', 'vi', 'zh-CN','zh-TW'],
// string, the name of the function for translating messages.
// Defaults to 'Yii::t'. This is used as a mark to find the messages to be
// translated. You may use a string for single function name or an array for
......
......@@ -17,41 +17,7 @@
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'The requested view "{name}" was not found.' => 'Die View-Datei "{name}" konnte nicht gefunden werden.',
'in {delta, plural, =1{a day} other{# days}}' => 'in {delta, plural, =1{einem Tag} other{# Tagen}}',
'in {delta, plural, =1{a minute} other{# minutes}}' => 'in {delta, plural, =1{einer Minute} other{# Minuten}}',
'in {delta, plural, =1{a month} other{# months}}' => 'in {delta, plural, =1{einem Monat} other{# Monaten}}',
'in {delta, plural, =1{a second} other{# seconds}}' => 'in {delta, plural, =1{einer Sekunde} other{# Sekunden}}',
'in {delta, plural, =1{a year} other{# years}}' => 'in {delta, plural, =1{einem Jahr} other{# Jahren}}',
'in {delta, plural, =1{an hour} other{# hours}}' => 'in {delta, plural, =1{einer Stunde} other{# Stunden}}',
'{delta, plural, =1{a day} other{# days}} ago' => 'vor {delta, plural, =1{einem Tag} other{# Tagen}}',
'{delta, plural, =1{a minute} other{# minutes}} ago' => 'vor {delta, plural, =1{einer Minute} other{# Minuten}}',
'{delta, plural, =1{a month} other{# months}} ago' => 'vor {delta, plural, =1{einem Monat} other{# Monaten}}',
'{delta, plural, =1{a second} other{# seconds}} ago' => 'vor {delta, plural, =1{einer Sekunde} other{# Sekunden}}',
'{delta, plural, =1{a year} other{# years}} ago' => 'vor {delta, plural, =1{einem Jahr} other{# Jahren}}',
'{delta, plural, =1{an hour} other{# hours}} ago' => 'vor {delta, plural, =1{einer Stunde} other{# Stunden}}',
'{nFormatted} B' => '{nFormatted} B',
'{nFormatted} GB' => '{nFormatted} GB',
'{nFormatted} GiB' => '{nFormatted} GiB',
'{nFormatted} KB' => '{nFormatted} KB',
'{nFormatted} KiB' => '{nFormatted} KiB',
'{nFormatted} MB' => '{nFormatted} MB',
'{nFormatted} MiB' => '{nFormatted} MiB',
'{nFormatted} PB' => '{nFormatted} PB',
'{nFormatted} PiB' => '{nFormatted} PiB',
'{nFormatted} TB' => '{nFormatted} TB',
'{nFormatted} TiB' => '{nFormatted} TiB',
'{nFormatted} {n, plural, =1{byte} other{bytes}}' => '{nFormatted} Byte',
'{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}' => '{nFormatted} GibiByte',
'{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}' => '{nFormatted} Gigabyte',
'{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}' => '{nFormatted} KibiByte',
'{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}' => '{nFormatted} Kilobyte',
'{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}' => '{nFormatted} MebiByte',
'{nFormatted} {n, plural, =1{megabyte} other{megabytes}}' => '{nFormatted} Megabyte',
'{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} PebiByte',
'{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} Petabyte',
'{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} TebiByte',
'{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} Terabyte',
'just now' => 'gerade jetzt',
'(not set)' => '(nicht gesetzt)',
'An internal server error occurred.' => 'Es ist ein interner Serverfehler aufgetreten.',
'Are you sure you want to delete this item?' => 'Wollen Sie diesen Eintrag wirklich löschen?',
......@@ -81,6 +47,7 @@ return [
'The image "{file}" is too large. The width cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Das Bild "{file}" ist zu groß. Es darf maximal {limit, number} Pixel breit sein.',
'The image "{file}" is too small. The height cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Das Bild "{file}" ist zu klein. Es muss mindestens {limit, number} Pixel hoch sein.',
'The image "{file}" is too small. The width cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Das Bild "{file}" ist zu klein. Es muss mindestens {limit, number} Pixel breit sein.',
'The requested view "{name}" was not found.' => 'Die View-Datei "{name}" konnte nicht gefunden werden.',
'The verification code is incorrect.' => 'Der Prüfcode ist falsch.',
'Total <b>{count, number}</b> {count, plural, one{item} other{items}}.' => 'Insgesamt <b>{count, number}</b> {count, plural, one{Eintrag} other{Einträge}}.',
'Unable to verify your data submission.' => 'Es ist nicht möglich, Ihre Dateneingabe zu prüfen.',
......@@ -91,6 +58,12 @@ return [
'Yes' => 'Ja',
'You are not allowed to perform this action.' => 'Sie dürfen diese Aktion nicht durchführen.',
'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => 'Sie können maximal {limit, number} {limit, plural, one{eine Datei} other{# Dateien}} hochladen.',
'in {delta, plural, =1{a day} other{# days}}' => 'in {delta, plural, =1{einem Tag} other{# Tagen}}',
'in {delta, plural, =1{a minute} other{# minutes}}' => 'in {delta, plural, =1{einer Minute} other{# Minuten}}',
'in {delta, plural, =1{a month} other{# months}}' => 'in {delta, plural, =1{einem Monat} other{# Monaten}}',
'in {delta, plural, =1{a second} other{# seconds}}' => 'in {delta, plural, =1{einer Sekunde} other{# Sekunden}}',
'in {delta, plural, =1{a year} other{# years}}' => 'in {delta, plural, =1{einem Jahr} other{# Jahren}}',
'in {delta, plural, =1{an hour} other{# hours}}' => 'in {delta, plural, =1{einer Stunde} other{# Stunden}}',
'the input value' => 'der eingegebene Wert',
'{attribute} "{value}" has already been taken.' => '{attribute} "{value}" wird bereits verwendet.',
'{attribute} cannot be blank.' => '{attribute} darf nicht leer sein.',
......@@ -113,4 +86,32 @@ return [
'{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.' => '{attribute} muss mindestens {min, number} Zeichen enthalten.',
'{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' => '{attribute} darf maximal {max, number} Zeichen enthalten.',
'{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '{attribute} muss aus genau {length, number} Zeichen bestehen.',
'{delta, plural, =1{a day} other{# days}} ago' => 'vor {delta, plural, =1{einem Tag} other{# Tagen}}',
'{delta, plural, =1{a minute} other{# minutes}} ago' => 'vor {delta, plural, =1{einer Minute} other{# Minuten}}',
'{delta, plural, =1{a month} other{# months}} ago' => 'vor {delta, plural, =1{einem Monat} other{# Monaten}}',
'{delta, plural, =1{a second} other{# seconds}} ago' => 'vor {delta, plural, =1{einer Sekunde} other{# Sekunden}}',
'{delta, plural, =1{a year} other{# years}} ago' => 'vor {delta, plural, =1{einem Jahr} other{# Jahren}}',
'{delta, plural, =1{an hour} other{# hours}} ago' => 'vor {delta, plural, =1{einer Stunde} other{# Stunden}}',
'{nFormatted} B' => '{nFormatted} B',
'{nFormatted} GB' => '{nFormatted} GB',
'{nFormatted} GiB' => '{nFormatted} GiB',
'{nFormatted} KB' => '{nFormatted} KB',
'{nFormatted} KiB' => '{nFormatted} KiB',
'{nFormatted} MB' => '{nFormatted} MB',
'{nFormatted} MiB' => '{nFormatted} MiB',
'{nFormatted} PB' => '{nFormatted} PB',
'{nFormatted} PiB' => '{nFormatted} PiB',
'{nFormatted} TB' => '{nFormatted} TB',
'{nFormatted} TiB' => '{nFormatted} TiB',
'{nFormatted} {n, plural, =1{byte} other{bytes}}' => '{nFormatted} Byte',
'{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}' => '{nFormatted} GibiByte',
'{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}' => '{nFormatted} Gigabyte',
'{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}' => '{nFormatted} KibiByte',
'{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}' => '{nFormatted} Kilobyte',
'{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}' => '{nFormatted} MebiByte',
'{nFormatted} {n, plural, =1{megabyte} other{megabytes}}' => '{nFormatted} Megabyte',
'{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} PebiByte',
'{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} Petabyte',
'{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} TebiByte',
'{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} Terabyte',
];
......@@ -7,23 +7,52 @@
namespace yii\validators;
use IntlDateFormatter;
use Yii;
use DateTime;
use yii\helpers\FormatConverter;
/**
* DateValidator verifies if the attribute represents a date, time or datetime in a proper format.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class DateValidator extends Validator
{
/**
* @var string the date format that the value being validated should follow.
* Please refer to <http://www.php.net/manual/en/datetime.createfromformat.php> on
* supported formats.
* This can be a date time pattern as described in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
*
* Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the PHP Datetime class.
* Please refer to <http://php.net/manual/en/datetime.createfromformat.php> on supported formats.
*
* If this property is not set, the default value will be obtained from `Yii::$app->formatter->dateFormat`, see [[\yii\i18n\Formatter::dateFormat]] for details.
*
* Here are some example values:
*
* ```php
* 'MM/dd/yyyy' // date in ICU format
* 'php:m/d/Y' // the same date in PHP format
* ```
*/
public $format = 'Y-m-d';
public $format;
/**
* @var string the locale ID that is used to localize the date parsing.
* This is only effective when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
* If not set, the locale of the [[\yii\base\Application::formatter|formatter]] will be used.
* See also [[\yii\i18n\Formatter::locale]].
*/
public $locale;
/**
* @var string the timezone to use for parsing date and time values.
* This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
* e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
* Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
* If this property is not set, [[\yii\base\Application::timeZone]] will be used.
*/
public $timeZone;
/**
* @var string the name of the attribute to receive the parsing result.
* When this property is not null and the validation is successful, the named attribute will
......@@ -31,6 +60,16 @@ class DateValidator extends Validator
*/
public $timestampAttribute;
/**
* @var array map of short format names to IntlDateFormatter constant values.
*/
private $_dateFormats = [
'short' => 3, // IntlDateFormatter::SHORT,
'medium' => 2, // IntlDateFormatter::MEDIUM,
'long' => 1, // IntlDateFormatter::LONG,
'full' => 0, // IntlDateFormatter::FULL,
];
/**
* @inheritdoc
......@@ -41,6 +80,15 @@ class DateValidator extends Validator
if ($this->message === null) {
$this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
}
if ($this->format === null) {
$this->format = Yii::$app->formatter->dateFormat;
}
if ($this->locale === null) {
$this->locale = Yii::$app->language;
}
if ($this->timeZone === null) {
$this->timeZone = Yii::$app->timeZone;
}
}
/**
......@@ -49,12 +97,11 @@ class DateValidator extends Validator
public function validateAttribute($object, $attribute)
{
$value = $object->$attribute;
$result = $this->validateValue($value);
if (!empty($result)) {
$this->addError($object, $attribute, $result[0], $result[1]);
$timestamp = $this->parseDateValue($value);
if ($timestamp === false) {
$this->addError($object, $attribute, $this->message, []);
} elseif ($this->timestampAttribute !== null) {
$date = DateTime::createFromFormat($this->format, $value);
$object->{$this->timestampAttribute} = $date->getTimestamp();
$object->{$this->timestampAttribute} = $timestamp;
}
}
......@@ -63,13 +110,42 @@ class DateValidator extends Validator
*/
protected function validateValue($value)
{
return $this->parseDateValue($value) === false ? [$this->message, []] : null;
}
protected function parseDateValue($value)
{
if (is_array($value)) {
return [$this->message, []];
return false;
}
$format = $this->format;
if (strncmp($this->format, 'php:', 4) === 0) {
$format = substr($format, 4);
} else {
if (extension_loaded('intl')) {
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, null, $format);
}
// enable strict parsing to avoid getting invalid date values
$formatter->setLenient(false);
return $formatter->parse($value);
} else {
// fallback to PHP if intl is not installed
$format = FormatConverter::convertDateIcuToPhp($format, 'date');
}
}
$date = DateTime::createFromFormat($this->format, $value);
$date = DateTime::createFromFormat($format, $value, new \DateTimeZone($this->timeZone));
$errors = DateTime::getLastErrors();
$invalid = $date === false || $errors['error_count'] || $errors['warning_count'];
return $invalid ? [$this->message, []] : null;
if ($date === false || $errors['error_count'] || $errors['warning_count']) {
return false;
} else {
// if no time was provided in the format string set time to 0 to get a simple date timestamp
if (strpbrk($format, 'HhGgis') === false) {
$date->setTime(0, 0, 0);
}
return $date->getTimestamp();
}
}
}
<?php
namespace yiiunit\framework\helpers;
use Yii;
use yii\helpers\FormatConverter;
use yii\i18n\Formatter;
use yiiunit\framework\i18n\IntlTestHelper;
use yiiunit\TestCase;
/**
* @group helpers
*/
class FormatConverterTest extends TestCase
{
protected function setUp()
{
parent::setUp();
IntlTestHelper::setIntlStatus($this);
$this->mockApplication([
'timeZone' => 'UTC',
'language' => 'ru-RU',
]);
}
protected function tearDown()
{
parent::tearDown();
IntlTestHelper::resetIntlStatus();
}
public function testIntlIcuToPhpShortForm()
{
$this->assertEquals('n/j/y', FormatConverter::convertDateIcuToPhp('short', 'date', 'en-US'));
$this->assertEquals('d.m.y', FormatConverter::convertDateIcuToPhp('short', 'date', 'de-DE'));
}
public function testIntlOneDigitIcu()
{
$formatter = new Formatter(['locale' => 'en-US']);
$this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'php:d.n.Y'));
$this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'd.M.yyyy'));
}
public function testOneDigitIcu()
{
$formatter = new Formatter(['locale' => 'en-US']);
$this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'php:d.n.Y'));
$this->assertEquals('24.8.2014', $formatter->asDate('2014-8-24', 'd.M.yyyy'));
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\i18n;
// override information about intl
use yiiunit\framework\i18n\FormatterTest;
function extension_loaded($name)
{
if ($name === 'intl' && FormatterTest::$enableIntl !== null) {
return FormatterTest::$enableIntl;
}
return \extension_loaded($name);
}
namespace yiiunit\framework\i18n;
use yii\base\InvalidParamException;
use yii\i18n\Formatter;
use yiiunit\TestCase;
use DateTime;
......@@ -31,8 +12,6 @@ use DateInterval;
*/
class FormatterTest extends TestCase
{
public static $enableIntl;
/**
* @var Formatter
*/
......@@ -42,17 +21,7 @@ class FormatterTest extends TestCase
{
parent::setUp();
// emulate disabled intl extension
// enable it only for tests prefixed with testIntl
static::$enableIntl = null;
if (strncmp($this->getName(false), 'testIntl', 8) === 0) {
if (!extension_loaded('intl')) {
$this->markTestSkipped('intl extension is not installed.');
}
static::$enableIntl = true;
} else {
static::$enableIntl = false;
}
IntlTestHelper::setIntlStatus($this);
$this->mockApplication([
'timeZone' => 'UTC',
......@@ -64,6 +33,7 @@ class FormatterTest extends TestCase
protected function tearDown()
{
parent::tearDown();
IntlTestHelper::resetIntlStatus();
$this->formatter = null;
}
......@@ -202,14 +172,11 @@ class FormatterTest extends TestCase
public function testAsBoolean()
{
$value = true;
$this->assertSame('Yes', $this->formatter->asBoolean($value));
$value = false;
$this->assertSame('No', $this->formatter->asBoolean($value));
$value = "111";
$this->assertSame('Yes', $this->formatter->asBoolean($value));
$value = "";
$this->assertSame('No', $this->formatter->asBoolean($value));
$this->assertSame('Yes', $this->formatter->asBoolean(true));
$this->assertSame('No', $this->formatter->asBoolean(false));
$this->assertSame('Yes', $this->formatter->asBoolean("111"));
$this->assertSame('No', $this->formatter->asBoolean(""));
$this->assertSame('No', $this->formatter->asBoolean(0));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asBoolean(null));
......@@ -233,6 +200,10 @@ class FormatterTest extends TestCase
$this->assertSame(date('n/j/y', $value), $this->formatter->asDate($value, 'short'));
$this->assertSame(date('F j, Y', $value), $this->formatter->asDate($value, 'long'));
// empty input
$this->assertSame('Jan 1, 1970', $this->formatter->asDate(''));
$this->assertSame('Jan 1, 1970', $this->formatter->asDate(0));
$this->assertSame('Jan 1, 1970', $this->formatter->asDate(false));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDate(null));
}
......@@ -240,6 +211,12 @@ class FormatterTest extends TestCase
public function testIntlAsTime()
{
$this->testAsTime();
// empty input
$this->formatter->locale = 'de-DE';
$this->assertSame('00:00:00', $this->formatter->asTime(''));
$this->assertSame('00:00:00', $this->formatter->asTime(0));
$this->assertSame('00:00:00', $this->formatter->asTime(false));
}
public function testAsTime()
......@@ -248,6 +225,10 @@ class FormatterTest extends TestCase
$this->assertSame(date('g:i:s A', $value), $this->formatter->asTime($value));
$this->assertSame(date('h:i:s A', $value), $this->formatter->asTime($value, 'php:h:i:s A'));
// empty input
$this->assertSame('12:00:00 AM', $this->formatter->asTime(''));
$this->assertSame('12:00:00 AM', $this->formatter->asTime(0));
$this->assertSame('12:00:00 AM', $this->formatter->asTime(false));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asTime(null));
}
......@@ -255,6 +236,12 @@ class FormatterTest extends TestCase
public function testIntlAsDatetime()
{
$this->testAsDatetime();
// empty input
$this->formatter->locale = 'de-DE';
$this->assertSame('01.01.1970 00:00:00', $this->formatter->asDatetime(''));
$this->assertSame('01.01.1970 00:00:00', $this->formatter->asDatetime(0));
$this->assertSame('01.01.1970 00:00:00', $this->formatter->asDatetime(false));
}
public function testAsDatetime()
......@@ -263,6 +250,10 @@ class FormatterTest extends TestCase
$this->assertSame(date('M j, Y g:i:s A', $value), $this->formatter->asDatetime($value));
$this->assertSame(date('Y/m/d h:i:s A', $value), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A'));
// empty input
$this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(''));
$this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(0));
$this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(false));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDatetime(null));
}
......@@ -275,13 +266,15 @@ class FormatterTest extends TestCase
$this->assertSame("$value", $this->formatter->asTimestamp(date('Y-m-d H:i:s', $value)));
// empty input
$this->assertSame("0", $this->formatter->asTimestamp(0));
$this->assertSame("0", $this->formatter->asTimestamp(false));
$this->assertSame("0", $this->formatter->asTimestamp(""));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asTimestamp(null));
}
// TODO test format conversion ICU/PHP
/**
* Test for dates before 1970
* https://github.com/yiisoft/yii2/issues/3126
......@@ -425,6 +418,14 @@ class FormatterTest extends TestCase
$this->assertSame('in a month', $this->formatter->asRelativeTime($this->buildDateSubIntervals('2014-03-03', [$interval_1_month]), $dateNow));
$this->assertSame('in 28 days', $this->formatter->asRelativeTime($dateThen, $dateNow));
// just now
$this->assertSame("just now", $this->formatter->asRelativeTime($t = time(), $t));
$this->assertSame("just now", $this->formatter->asRelativeTime(0, 0));
// empty input
$this->assertSame("just now", $this->formatter->asRelativeTime(false, 0));
$this->assertSame("just now", $this->formatter->asRelativeTime("", 0));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asRelativeTime(null));
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asRelativeTime(null, time()));
......@@ -460,7 +461,7 @@ class FormatterTest extends TestCase
*/
public function testAsIntegerException()
{
$this->assertSame("0", $this->formatter->asInteger('a'));
$this->formatter->asInteger('a');
}
/**
......@@ -468,7 +469,23 @@ class FormatterTest extends TestCase
*/
public function testAsIntegerException2()
{
$this->assertSame("0", $this->formatter->asInteger('-123abc'));
$this->formatter->asInteger('-123abc');
}
/**
* @expectedException \yii\base\InvalidParamException
*/
public function testAsIntegerException3()
{
$this->formatter->asInteger('');
}
/**
* @expectedException \yii\base\InvalidParamException
*/
public function testAsIntegerException4()
{
$this->formatter->asInteger(false);
}
public function testIntlAsDecimal()
......@@ -696,6 +713,9 @@ class FormatterTest extends TestCase
$this->formatter->numberFormatterOptions = [];
$this->assertSame("1,001 KiB", $this->formatter->asShortSize(1025, 3));
// empty values
$this->assertSame('0 B', $this->formatter->asShortSize(0));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asSize(null));
}
......@@ -723,6 +743,9 @@ class FormatterTest extends TestCase
$this->formatter->decimalSeparator = ',';
$this->assertSame("1,001 KiB", $this->formatter->asShortSize(1025, 3));
// empty values
$this->assertSame('0 bytes', $this->formatter->asSize(0));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asSize(null));
}
......
<?php
// override information about intl
namespace yiiunit\framework\i18n {
use yiiunit\TestCase;
class IntlTestHelper {
public static $enableIntl;
/**
* emulate disabled intl extension
*
* enable it only for tests prefixed with testIntl
* @param Testcase $test
*/
public static function setIntlStatus($test)
{
static::$enableIntl = null;
if (strncmp($test->getName(false), 'testIntl', 8) === 0) {
if (!extension_loaded('intl')) {
$test->markTestSkipped('intl extension is not installed.');
}
static::$enableIntl = true;
} else {
static::$enableIntl = false;
}
}
public static function resetIntlStatus()
{
static::$enableIntl = null;
}
}
}
namespace yii\i18n {
use yiiunit\framework\i18n\IntlTestHelper;
if (!function_exists('yii\i18n\extension_loaded')) {
function extension_loaded($name)
{
if ($name === 'intl' && IntlTestHelper::$enableIntl !== null) {
return IntlTestHelper::$enableIntl;
}
return \extension_loaded($name);
}
}
}
namespace yii\helpers {
use yiiunit\framework\i18n\IntlTestHelper;
if (!function_exists('yii\helpers\extension_loaded')) {
function extension_loaded($name)
{
if ($name === 'intl' && IntlTestHelper::$enableIntl !== null) {
return IntlTestHelper::$enableIntl;
}
return \extension_loaded($name);
}
}
}
namespace yii\validators {
use yiiunit\framework\i18n\IntlTestHelper;
if (!function_exists('yii\validators\extension_loaded')) {
function extension_loaded($name)
{
if ($name === 'intl' && IntlTestHelper::$enableIntl !== null) {
return IntlTestHelper::$enableIntl;
}
return \extension_loaded($name);
}
}
}
......@@ -5,6 +5,7 @@ namespace yiiunit\framework\validators;
use DateTime;
use yii\validators\DateValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\framework\i18n\IntlTestHelper;
use yiiunit\TestCase;
/**
......@@ -15,7 +16,19 @@ class DateValidatorTest extends TestCase
protected function setUp()
{
parent::setUp();
$this->mockApplication();
IntlTestHelper::setIntlStatus($this);
$this->mockApplication([
'timeZone' => 'UTC',
'language' => 'ru-RU',
]);
}
protected function tearDown()
{
parent::tearDown();
IntlTestHelper::resetIntlStatus();
}
public function testEnsureMessageIsSet()
......@@ -24,26 +37,79 @@ class DateValidatorTest extends TestCase
$this->assertTrue($val->message !== null && strlen($val->message) > 1);
}
public function testIntlValidateValue()
{
$this->testValidateValue();
$this->mockApplication([
'language' => 'en-GB',
'components' => [
'formatter' => [
'dateFormat' => 'short',
]
]
]);
$val = new DateValidator();
$this->assertTrue($val->validate('31/5/2017'));
$this->assertFalse($val->validate('5/31/2017'));
$val = new DateValidator(['format' => 'short', 'locale' => 'en-GB']);
$this->assertTrue($val->validate('31/5/2017'));
$this->assertFalse($val->validate('5/31/2017'));
$this->mockApplication([
'language' => 'de-DE',
'components' => [
'formatter' => [
'dateFormat' => 'short',
]
]
]);
$val = new DateValidator();
$this->assertTrue($val->validate('31.5.2017'));
$this->assertFalse($val->validate('5.31.2017'));
$val = new DateValidator(['format' => 'short', 'locale' => 'de-DE']);
$this->assertTrue($val->validate('31.5.2017'));
$this->assertFalse($val->validate('5.31.2017'));
}
public function testValidateValue()
{
$val = new DateValidator;
// test PHP format
$val = new DateValidator(['format' => 'php:Y-m-d']);
$this->assertFalse($val->validate('3232-32-32'));
$this->assertTrue($val->validate('2013-09-13'));
$this->assertFalse($val->validate('31.7.2013'));
$this->assertFalse($val->validate('31-7-2013'));
$this->assertFalse($val->validate(time()));
$val->format = 'U';
$val->format = 'php:U';
$this->assertTrue($val->validate(time()));
$val->format = 'd.m.Y';
$val->format = 'php:d.m.Y';
$this->assertTrue($val->validate('31.7.2013'));
$val->format = 'php:Y-m-!d H:i:s';
$this->assertTrue($val->validate('2009-02-15 15:16:17'));
// test ICU format
$val = new DateValidator(['format' => 'yyyy-MM-dd']);
$this->assertFalse($val->validate('3232-32-32'));
$this->assertTrue($val->validate('2013-09-13'));
$this->assertFalse($val->validate('31.7.2013'));
$this->assertFalse($val->validate('31-7-2013'));
$this->assertFalse($val->validate(time()));
$val->format = 'dd.MM.yyyy';
$this->assertTrue($val->validate('31.7.2013'));
$val->format = 'Y-m-!d H:i:s';
$val->format = 'yyyy-MM-dd HH:mm:ss';
$this->assertTrue($val->validate('2009-02-15 15:16:17'));
}
public function testValidateAttribute()
public function testIntlValidateAttributePHP()
{
$this->testValidateAttributePHPFormat();
}
public function testValidateAttributePHPFormat()
{
// error-array-add
$val = new DateValidator;
$val = new DateValidator(['format' => 'php:Y-m-d']);
$model = new FakedValidationModel;
$model->attr_date = '2013-09-13';
$val->validateAttribute($model, 'attr_date');
......@@ -53,7 +119,7 @@ class DateValidatorTest extends TestCase
$val->validateAttribute($model, 'attr_date');
$this->assertTrue($model->hasErrors('attr_date'));
//// timestamp attribute
$val = new DateValidator(['timestampAttribute' => 'attr_timestamp']);
$val = new DateValidator(['format' => 'php:Y-m-d', 'timestampAttribute' => 'attr_timestamp']);
$model = new FakedValidationModel;
$model->attr_date = '2013-09-13';
$model->attr_timestamp = true;
......@@ -61,10 +127,48 @@ class DateValidatorTest extends TestCase
$this->assertFalse($model->hasErrors('attr_date'));
$this->assertFalse($model->hasErrors('attr_timestamp'));
$this->assertEquals(
DateTime::createFromFormat($val->format, '2013-09-13')->getTimestamp(),
mktime(0, 0, 0, 9, 13, 2013), // 2013-09-13
// DateTime::createFromFormat('Y-m-d', '2013-09-13')->getTimestamp(),
$model->attr_timestamp
);
$val = new DateValidator();
$val = new DateValidator(['format' => 'php:Y-m-d']);
$model = FakedValidationModel::createWithAttributes(['attr_date' => []]);
$val->validateAttribute($model, 'attr_date');
$this->assertTrue($model->hasErrors('attr_date'));
}
public function testIntlValidateAttributeICU()
{
$this->testValidateAttributeICUFormat();
}
public function testValidateAttributeICUFormat()
{
// error-array-add
$val = new DateValidator(['format' => 'yyyy-MM-dd']);
$model = new FakedValidationModel;
$model->attr_date = '2013-09-13';
$val->validateAttribute($model, 'attr_date');
$this->assertFalse($model->hasErrors('attr_date'));
$model = new FakedValidationModel;
$model->attr_date = '1375293913';
$val->validateAttribute($model, 'attr_date');
$this->assertTrue($model->hasErrors('attr_date'));
//// timestamp attribute
$val = new DateValidator(['format' => 'yyyy-MM-dd', 'timestampAttribute' => 'attr_timestamp']);
$model = new FakedValidationModel;
$model->attr_date = '2013-09-13';
$model->attr_timestamp = true;
$val->validateAttribute($model, 'attr_date');
$this->assertFalse($model->hasErrors('attr_date'));
$this->assertFalse($model->hasErrors('attr_timestamp'));
$this->assertEquals(
mktime(0, 0, 0, 9, 13, 2013), // 2013-09-13
// DateTime::createFromFormat('Y-m-d', '2013-09-13')->getTimestamp(),
$model->attr_timestamp
);
$val = new DateValidator(['format' => 'yyyy-MM-dd']);
$model = FakedValidationModel::createWithAttributes(['attr_date' => []]);
$val->validateAttribute($model, 'attr_date');
$this->assertTrue($model->hasErrors('attr_date'));
......
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