DateValidator.php 5.9 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8 9
namespace yii\validators;

10
use IntlDateFormatter;
Qiang Xue committed
11 12
use Yii;
use DateTime;
13
use yii\helpers\FormatConverter;
Qiang Xue committed
14

w  
Qiang Xue committed
15
/**
Qiang Xue committed
16
 * DateValidator verifies if the attribute represents a date, time or datetime in a proper format.
w  
Qiang Xue committed
17 18
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
19
 * @author Carsten Brandt <mail@cebe.cc>
Alexander Makarov committed
20
 * @since 2.0
w  
Qiang Xue committed
21
 */
Alexander Makarov committed
22
class DateValidator extends Validator
w  
Qiang Xue committed
23
{
24 25
    /**
     * @var string the date format that the value being validated should follow.
26 27 28 29 30 31 32 33 34 35 36 37 38
     * 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
     * ```
39
     */
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    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;
56 57 58 59 60 61
    /**
     * @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
     * receive the parsing result.
     */
    public $timestampAttribute;
w  
Qiang Xue committed
62

63 64 65 66 67 68 69 70 71 72
    /**
     * @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,
    ];

73

74 75 76 77 78 79 80 81 82
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if ($this->message === null) {
            $this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
        }
83 84 85 86 87 88 89 90 91
        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;
        }
92
    }
Qiang Xue committed
93

94 95 96
    /**
     * @inheritdoc
     */
Qiang Xue committed
97
    public function validateAttribute($model, $attribute)
98
    {
Qiang Xue committed
99
        $value = $model->$attribute;
100 101
        $timestamp = $this->parseDateValue($value);
        if ($timestamp === false) {
Qiang Xue committed
102
            $this->addError($model, $attribute, $this->message, []);
103
        } elseif ($this->timestampAttribute !== null) {
Qiang Xue committed
104
            $model->{$this->timestampAttribute} = $timestamp;
105 106
        }
    }
Qiang Xue committed
107

108 109 110 111
    /**
     * @inheritdoc
     */
    protected function validateValue($value)
112 113 114 115
    {
        return $this->parseDateValue($value) === false ? [$this->message, []] : null;
    }

116 117 118 119 120 121
    /**
     * Parses date string into UNIX timestamp
     *
     * @param string $value string representing date
     * @return boolean|integer UNIX timestamp or false on failure
     */
122
    protected function parseDateValue($value)
123 124
    {
        if (is_array($value)) {
125 126 127 128 129 130 131 132 133 134 135 136 137 138
            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);
139 140 141 142

                // There should not be a warning thrown by parse() but this seems to be the case on windows so we suppress it here
                // See https://github.com/yiisoft/yii2/issues/5962 and https://bugs.php.net/bug.php?id=68528
                return @$formatter->parse($value);
143 144 145 146
            } else {
                // fallback to PHP if intl is not installed
                $format = FormatConverter::convertDateIcuToPhp($format, 'date');
            }
147
        }
148
        $date = DateTime::createFromFormat($format, $value, new \DateTimeZone($this->timeZone));
149
        $errors = DateTime::getLastErrors();
150 151 152 153 154 155 156 157 158
        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();
        }
159
    }
w  
Qiang Xue committed
160
}