DateValidator.php
13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\validators;
use DateTime;
use IntlDateFormatter;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\FormatConverter;
/**
* DateValidator verifies if the attribute represents a date, time or datetime in a proper [[format]].
*
* It can also parse internationalized dates in a specific [[locale]] like e.g. `12 мая 2014` when [[format]]
* is configured to use a time pattern in ICU format.
*
* It is further possible to limit the date within a certain range using [[min]] and [[max]].
*
* Additional to validating the date it can also export the parsed timestamp as a machine readable format
* which can be configured using [[timestampAttribute]].
*
* @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.
* 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
* 'MM/dd/yyyy HH:mm' // not only dates but also times can be validated
* ```
*
* **Note:** the underlying date parsers being used vary dependent on the format. If you use the ICU format and
* the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed, the [IntlDateFormatter](http://php.net/manual/en/intldateformatter.parse.php)
* is used to parse the input value. In all other cases the PHP [DateTime](http://php.net/manual/en/datetime.createfromformat.php) class
* is used. The IntlDateFormatter has the advantage that it can parse international dates like `12. Mai 2015` or `12 мая 2014`, while the
* PHP parser is limited to English only. The PHP parser however is more strict about the input format as it will not accept
* `12.05.05` for the format `php:d.m.Y`, but the IntlDateFormatter will accept it for the format `dd-MM-yyyy`.
* If you need to use the IntlDateFormatter you can avoid this problem by specifying a [[min|minimum date]].
*/
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
* receive the parsing result.
*
* This can be the same attribute as the one being validated. If this is the case,
* the original value will be overwritten with the timestamp value after successful validation.
* @see timestampAttributeFormat
* @see timestampAttributeTimeZone
*/
public $timestampAttribute;
/**
* @var string the format to use when populating the [[timestampAttribute]].
* The format can be specified in the same way as for [[format]].
*
* If not set, [[timestampAttribute]] will receive a UNIX timestamp.
* If [[timestampAttribute]] is not set, this property will be ignored.
* @see format
* @see timestampAttribute
* @since 2.0.4
*/
public $timestampAttributeFormat;
/**
* @var string the timezone to use when populating the [[timestampAttribute]]. Defaults to `UTC`.
*
* 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 [[timestampAttributeFormat]] is not set, this property will be ignored.
* @see timestampAttributeFormat
* @since 2.0.4
*/
public $timestampAttributeTimeZone = 'UTC';
/**
* @var integer|string upper limit of the date. Defaults to null, meaning no upper limit.
* This can be a unix timestamp or a string representing a date time value.
* If this property is a string, [[format]] will be used to parse it.
* @see tooBig for the customized message used when the date is too big.
* @since 2.0.4
*/
public $max;
/**
* @var integer|string lower limit of the date. Defaults to null, meaning no lower limit.
* This can be a unix timestamp or a string representing a date time value.
* If this property is a string, [[format]] will be used to parse it.
* @see tooSmall for the customized message used when the date is too small.
* @since 2.0.4
*/
public $min;
/**
* @var string user-defined error message used when the value is bigger than [[max]].
* @since 2.0.4
*/
public $tooBig;
/**
* @var string user-defined error message used when the value is smaller than [[min]].
* @since 2.0.4
*/
public $tooSmall;
/**
* @var string user friendly value of upper limit to display in the error message.
* If this property is null, the value of [[max]] will be used (before parsing).
* @since 2.0.4
*/
public $maxString;
/**
* @var string user friendly value of lower limit to display in the error message.
* If this property is null, the value of [[min]] will be used (before parsing).
* @since 2.0.4
*/
public $minString;
/**
* @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
*/
public function init()
{
parent::init();
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;
}
if ($this->min !== null && $this->tooSmall === null) {
$this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
}
if ($this->max !== null && $this->tooBig === null) {
$this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
}
if ($this->maxString === null) {
$this->maxString = (string) $this->max;
}
if ($this->minString === null) {
$this->minString = (string) $this->min;
}
if ($this->max !== null && is_string($this->max)) {
$timestamp = $this->parseDateValue($this->max);
if ($timestamp === false) {
throw new InvalidConfigException("Invalid max date value: {$this->max}");
}
$this->max = $timestamp;
}
if ($this->min !== null && is_string($this->min)) {
$timestamp = $this->parseDateValue($this->min);
if ($timestamp === false) {
throw new InvalidConfigException("Invalid min date value: {$this->min}");
}
$this->min = $timestamp;
}
}
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$timestamp = $this->parseDateValue($value);
if ($timestamp === false) {
$this->addError($model, $attribute, $this->message, []);
} elseif ($this->min !== null && $timestamp < $this->min) {
$this->addError($model, $attribute, $this->tooSmall, ['min' => $this->minString]);
} elseif ($this->max !== null && $timestamp > $this->max) {
$this->addError($model, $attribute, $this->tooBig, ['max' => $this->maxString]);
} elseif ($this->timestampAttribute !== null) {
if ($this->timestampAttributeFormat === null) {
$model->{$this->timestampAttribute} = $timestamp;
} else {
$model->{$this->timestampAttribute} = $this->formatTimestamp($timestamp, $this->timestampAttributeFormat);
}
}
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
$timestamp = $this->parseDateValue($value);
if ($timestamp === false) {
return [$this->message, []];
} elseif ($this->min !== null && $timestamp < $this->min) {
return [$this->tooSmall, ['min' => $this->minString]];
} elseif ($this->max !== null && $timestamp > $this->max) {
return [$this->tooBig, ['max' => $this->maxString]];
} else {
return null;
}
}
/**
* Parses date string into UNIX timestamp
*
* @param string $value string representing date
* @return integer|false a UNIX timestamp or `false` on failure.
*/
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')) {
return $this->parseDateValueIntl($value, $format);
} else {
// fallback to PHP if intl is not installed
$format = FormatConverter::convertDateIcuToPhp($format, 'date');
}
}
return $this->parseDateValuePHP($value, $format);
}
/**
* Parses a date value using the IntlDateFormatter::parse()
* @param string $value string representing date
* @param string $format the expected date format
* @return integer|boolean a UNIX timestamp or `false` on failure.
*/
private function parseDateValueIntl($value, $format)
{
if (isset($this->_dateFormats[$format])) {
$formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, 'UTC');
} else {
// if no time was provided in the format string set time to 0 to get a simple date timestamp
$hasTimeInfo = (strpbrk($format, 'ahHkKmsSA') !== false);
$formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $hasTimeInfo ? $this->timeZone : 'UTC', null, $format);
}
// enable strict parsing to avoid getting invalid date values
$formatter->setLenient(false);
// 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
$parsePos = 0;
$parsedDate = @$formatter->parse($value, $parsePos);
if ($parsedDate === false || $parsePos !== mb_strlen($value, Yii::$app ? Yii::$app->charset : 'UTF-8')) {
return false;
}
return $parsedDate;
}
/**
* Parses a date value using the DateTime::createFromFormat()
* @param string $value string representing date
* @param string $format the expected date format
* @return integer|boolean a UNIX timestamp or `false` on failure.
*/
private function parseDateValuePHP($value, $format)
{
// if no time was provided in the format string set time to 0 to get a simple date timestamp
$hasTimeInfo = (strpbrk($format, 'HhGgis') !== false);
$date = DateTime::createFromFormat($format, $value, new \DateTimeZone($hasTimeInfo ? $this->timeZone : 'UTC'));
$errors = DateTime::getLastErrors();
if ($date === false || $errors['error_count'] || $errors['warning_count']) {
return false;
}
if (!$hasTimeInfo) {
$date->setTime(0, 0, 0);
}
return $date->getTimestamp();
}
/**
* Formats a timestamp using the specified format
* @param integer $timestamp
* @param string $format
* @return string
*/
private function formatTimestamp($timestamp, $format)
{
if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4);
} else {
$format = FormatConverter::convertDateIcuToPhp($format, 'date');
}
$date = new DateTime();
$date->setTimestamp($timestamp);
$date->setTimezone(new \DateTimeZone($this->timestampAttributeTimeZone));
return $date->format($format);
}
}