mirror of
https://github.com/yiisoft/yii2.git
synced 2025-08-18 09:17:15 +08:00
Refactored DateValidator to support ICU format
This commit is contained in:
@ -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)
|
||||
{
|
||||
if (is_array($value)) {
|
||||
return [$this->message, []];
|
||||
}
|
||||
$date = DateTime::createFromFormat($this->format, $value);
|
||||
$errors = DateTime::getLastErrors();
|
||||
$invalid = $date === false || $errors['error_count'] || $errors['warning_count'];
|
||||
return $this->parseDateValue($value) === false ? [$this->message, []] : null;
|
||||
}
|
||||
|
||||
return $invalid ? [$this->message, []] : null;
|
||||
protected function parseDateValue($value)
|
||||
{
|
||||
if (is_array($value)) {
|
||||
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($format, $value, new \DateTimeZone($this->timeZone));
|
||||
$errors = DateTime::getLastErrors();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user