DateValidator   F
last analyzed

Complexity

Total Complexity 68

Size/Duplication

Total Lines 440
Duplicated Lines 0 %

Test Coverage

Coverage 90.98%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 142
dl 0
loc 440
ccs 111
cts 122
cp 0.9098
rs 2.96
c 1
b 1
f 0
wmc 68

9 Methods

Rating   Name   Duplication   Size   Complexity  
A parseDateValueFormat() 0 17 4
F init() 0 48 20
B parseDateValuePHP() 0 17 9
A parseDateValue() 0 4 1
C validateAttribute() 0 31 14
A parseDateValueIntl() 0 16 6
A formatTimestamp() 0 13 2
A validateValue() 0 12 6
A getIntlDateFormatter() 0 25 6

How to fix   Complexity   

Complex Class

Complex classes like DateValidator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DateValidator, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\validators;
10
11
use DateTime;
12
use DateTimeZone;
13
use Exception;
14
use IntlDateFormatter;
15
use Yii;
16
use yii\base\InvalidConfigException;
17
use yii\helpers\FormatConverter;
18
19
/**
20
 * DateValidator verifies if the attribute represents a date, time or datetime in a proper [[format]].
21
 *
22
 * It can also parse internationalized dates in a specific [[locale]] like e.g. `12 мая 2014` when [[format]]
23
 * is configured to use a time pattern in ICU format.
24
 *
25
 * It is further possible to limit the date within a certain range using [[min]] and [[max]].
26
 *
27
 * Additional to validating the date it can also export the parsed timestamp as a machine readable format
28
 * which can be configured using [[timestampAttribute]]. For values that include time information (not date-only values)
29
 * also the time zone will be adjusted. The time zone of the input value is assumed to be the one specified by the [[timeZone]]
30
 * property and the target timeZone will be UTC when [[timestampAttributeFormat]] is `null` (exporting as UNIX timestamp)
31
 * or [[timestampAttributeTimeZone]] otherwise. If you want to avoid the time zone conversion, make sure that [[timeZone]] and
32
 * [[timestampAttributeTimeZone]] are the same.
33
 *
34
 * @author Qiang Xue <[email protected]>
35
 * @author Carsten Brandt <[email protected]>
36
 * @since 2.0
37
 */
38
class DateValidator extends Validator
39
{
40
    /**
41
     * Constant for specifying the validation [[type]] as a date value, used for validation with intl short format.
42
     * @since 2.0.8
43
     * @see type
44
     */
45
    const TYPE_DATE = 'date';
46
    /**
47
     * Constant for specifying the validation [[type]] as a datetime value, used for validation with intl short format.
48
     * @since 2.0.8
49
     * @see type
50
     */
51
    const TYPE_DATETIME = 'datetime';
52
    /**
53
     * Constant for specifying the validation [[type]] as a time value, used for validation with intl short format.
54
     * @since 2.0.8
55
     * @see type
56
     */
57
    const TYPE_TIME = 'time';
58
59
    /**
60
     * @var string the type of the validator. Indicates, whether a date, time or datetime value should be validated.
61
     * This property influences the default value of [[format]] and also sets the correct behavior when [[format]] is one of the intl
62
     * short formats, `short`, `medium`, `long`, or `full`.
63
     *
64
     * This is only effective when the [PHP intl extension](https://www.php.net/manual/en/book.intl.php) is installed.
65
     *
66
     * This property can be set to the following values:
67
     *
68
     * - [[TYPE_DATE]] - (default) for validating date values only, that means only values that do not include a time range are valid.
69
     * - [[TYPE_DATETIME]] - for validating datetime values, that contain a date part as well as a time part.
70
     * - [[TYPE_TIME]] - for validating time values, that contain no date information.
71
     *
72
     * @since 2.0.8
73
     */
74
    public $type = self::TYPE_DATE;
75
    /**
76
     * @var string|null the date format that the value being validated should follow.
77
     * This can be a date time pattern as described in the [ICU manual](https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax).
78
     *
79
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the PHP Datetime class.
80
     * Please refer to <https://www.php.net/manual/en/datetime.createfromformat.php> on supported formats.
81
     *
82
     * If this property is not set, the default value will be obtained from `Yii::$app->formatter->dateFormat`, see [[\yii\i18n\Formatter::dateFormat]] for details.
83
     * Since version 2.0.8 the default value will be determined from different formats of the formatter class,
84
     * dependent on the value of [[type]]:
85
     *
86
     * - if type is [[TYPE_DATE]], the default value will be taken from [[\yii\i18n\Formatter::dateFormat]],
87
     * - if type is [[TYPE_DATETIME]], it will be taken from [[\yii\i18n\Formatter::datetimeFormat]],
88
     * - and if type is [[TYPE_TIME]], it will be [[\yii\i18n\Formatter::timeFormat]].
89
     *
90
     * Here are some example values:
91
     *
92
     * ```php
93
     * 'MM/dd/yyyy' // date in ICU format
94
     * 'php:m/d/Y' // the same date in PHP format
95
     * 'MM/dd/yyyy HH:mm' // not only dates but also times can be validated
96
     * ```
97
     *
98
     * **Note:** the underlying date parsers being used vary dependent on the format. If you use the ICU format and
99
     * the [PHP intl extension](https://www.php.net/manual/en/book.intl.php) is installed, the [IntlDateFormatter](https://www.php.net/manual/en/intldateformatter.parse.php)
100
     * is used to parse the input value. In all other cases the PHP [DateTime](https://www.php.net/manual/en/datetime.createfromformat.php) class
101
     * is used. The IntlDateFormatter has the advantage that it can parse international dates like `12. Mai 2015` or `12 мая 2014`, while the
102
     * PHP parser is limited to English only. The PHP parser however is more strict about the input format as it will not accept
103
     * `12.05.05` for the format `php:d.m.Y`, but the IntlDateFormatter will accept it for the format `dd.MM.yyyy`.
104
     * If you need to use the IntlDateFormatter you can avoid this problem by specifying a [[min|minimum date]].
105
     */
106
    public $format;
107
    /**
108
     * @var string|null the locale ID that is used to localize the date parsing.
109
     * This is only effective when the [PHP intl extension](https://www.php.net/manual/en/book.intl.php) is installed.
110
     * If not set, the locale of the [[\yii\base\Application::formatter|formatter]] will be used.
111
     * See also [[\yii\i18n\Formatter::locale]].
112
     */
113
    public $locale;
114
    /**
115
     * @var string|null the timezone to use for parsing date and time values.
116
     * This can be any value that may be passed to [date_default_timezone_set()](https://www.php.net/manual/en/function.date-default-timezone-set.php)
117
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
118
     * Refer to the [php manual](https://www.php.net/manual/en/timezones.php) for available timezones.
119
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
120
     */
121
    public $timeZone;
122
    /**
123
     * @var string|null the name of the attribute to receive the parsing result.
124
     * When this property is not null and the validation is successful, the named attribute will
125
     * receive the parsing result.
126
     *
127
     * This can be the same attribute as the one being validated. If this is the case,
128
     * the original value will be overwritten with the timestamp value after successful validation.
129
     *
130
     * Note, that when using this property, the input value will be converted to a unix timestamp, which by definition
131
     * is in [[$defaultTimeZone|default UTC time zone]], so a conversion from the [[$timeZone|input time zone]] to
132
     * the default one will be performed. If you want to change the default time zone, set the [[$defaultTimeZone]] property.
133
     * When defining [[$timestampAttributeFormat]] you can further control the conversion by setting
134
     * [[$timestampAttributeTimeZone]] to a different value than `'UTC'`.
135
     *
136
     * @see timestampAttributeFormat
137
     * @see timestampAttributeTimeZone
138
     */
139
    public $timestampAttribute;
140
    /**
141
     * @var string|null the format to use when populating the [[timestampAttribute]].
142
     * The format can be specified in the same way as for [[format]].
143
     *
144
     * If not set, [[timestampAttribute]] will receive a UNIX timestamp.
145
     * If [[timestampAttribute]] is not set, this property will be ignored.
146
     * @see format
147
     * @see timestampAttribute
148
     * @since 2.0.4
149
     */
150
    public $timestampAttributeFormat;
151
    /**
152
     * @var string the timezone to use when populating the [[timestampAttribute]] with [[timestampAttributeFormat]]. Defaults to `UTC`.
153
     *
154
     * This can be any value that may be passed to [date_default_timezone_set()](https://www.php.net/manual/en/function.date-default-timezone-set.php)
155
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
156
     * Refer to the [php manual](https://www.php.net/manual/en/timezones.php) for available timezones.
157
     *
158
     * If [[timestampAttributeFormat]] is not set, this property will be ignored.
159
     * @see timestampAttributeFormat
160
     * @since 2.0.4
161
     */
162
    public $timestampAttributeTimeZone = 'UTC';
163
    /**
164
     * @var int|string|null upper limit of the date. Defaults to null, meaning no upper limit.
165
     * This can be a unix timestamp or a string representing a date time value.
166
     * If this property is a string, [[format]] will be used to parse it.
167
     * @see tooBig for the customized message used when the date is too big.
168
     * @since 2.0.4
169
     */
170
    public $max;
171
    /**
172
     * @var int|string|null lower limit of the date. Defaults to null, meaning no lower limit.
173
     * This can be a unix timestamp or a string representing a date time value.
174
     * If this property is a string, [[format]] will be used to parse it.
175
     * @see tooSmall for the customized message used when the date is too small.
176
     * @since 2.0.4
177
     */
178
    public $min;
179
    /**
180
     * @var string user-defined error message used when the value is bigger than [[max]].
181
     * @since 2.0.4
182
     */
183
    public $tooBig;
184
    /**
185
     * @var string user-defined error message used when the value is smaller than [[min]].
186
     * @since 2.0.4
187
     */
188
    public $tooSmall;
189
    /**
190
     * @var string|null user friendly value of upper limit to display in the error message.
191
     * If this property is null, the value of [[max]] will be used (before parsing).
192
     * @since 2.0.4
193
     */
194
    public $maxString;
195
    /**
196
     * @var string|null user friendly value of lower limit to display in the error message.
197
     * If this property is null, the value of [[min]] will be used (before parsing).
198
     * @since 2.0.4
199
     */
200
    public $minString;
201
    /**
202
     * @var bool set this parameter to true if you need strict date format validation (e.g. only such dates pass
203
     * validation for the following format 'yyyy-MM-dd': '0011-03-25', '2019-04-30' etc. and not '18-05-15',
204
     * '2017-Mar-14' etc. which pass validation if this parameter is set to false)
205
     * @since 2.0.22
206
     */
207
    public $strictDateFormat = false;
208
    /**
209
     * @var string the default timezone used for parsing when no time parts are provided in the format.
210
     * See [[timestampAttributeTimeZone]] for more description.
211
     * @since 2.0.39
212
     */
213
    public $defaultTimeZone = 'UTC';
214
215
    /**
216
     * @var array map of short format names to IntlDateFormatter constant values.
217
     */
218
    private $_dateFormats = [
219
        'short' => 3, // IntlDateFormatter::SHORT,
220
        'medium' => 2, // IntlDateFormatter::MEDIUM,
221
        'long' => 1, // IntlDateFormatter::LONG,
222
        'full' => 0, // IntlDateFormatter::FULL,
223
    ];
224
225
226
    /**
227
     * {@inheritdoc}
228
     */
229 206
    public function init()
230
    {
231 206
        parent::init();
232 206
        if ($this->message === null) {
233 206
            $this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
234
        }
235 206
        if ($this->format === null) {
236 7
            if ($this->type === self::TYPE_DATE) {
237 4
                $this->format = Yii::$app->formatter->dateFormat;
238 3
            } elseif ($this->type === self::TYPE_DATETIME) {
239 3
                $this->format = Yii::$app->formatter->datetimeFormat;
240
            } elseif ($this->type === self::TYPE_TIME) {
241
                $this->format = Yii::$app->formatter->timeFormat;
242
            } else {
243
                throw new InvalidConfigException('Unknown validation type set for DateValidator::$type: ' . $this->type);
244
            }
245
        }
246 206
        if ($this->locale === null) {
247 205
            $this->locale = Yii::$app->language;
248
        }
249 206
        if ($this->timeZone === null) {
250 89
            $this->timeZone = Yii::$app->timeZone;
251
        }
252 206
        if ($this->min !== null && $this->tooSmall === null) {
253 6
            $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
254
        }
255 206
        if ($this->max !== null && $this->tooBig === null) {
256 4
            $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
257
        }
258 206
        if ($this->maxString === null) {
259 206
            $this->maxString = (string)$this->max;
260
        }
261 206
        if ($this->minString === null) {
262 206
            $this->minString = (string)$this->min;
263
        }
264 206
        if ($this->max !== null && is_string($this->max)) {
265 4
            $timestamp = $this->parseDateValue($this->max);
266 4
            if ($timestamp === false) {
267
                throw new InvalidConfigException("Invalid max date value: {$this->max}");
268
            }
269 4
            $this->max = $timestamp;
270
        }
271 206
        if ($this->min !== null && is_string($this->min)) {
272 6
            $timestamp = $this->parseDateValue($this->min);
273 6
            if ($timestamp === false) {
274
                throw new InvalidConfigException("Invalid min date value: {$this->min}");
275
            }
276 6
            $this->min = $timestamp;
277
        }
278
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283 169
    public function validateAttribute($model, $attribute)
284
    {
285 169
        $value = $model->$attribute;
286 169
        if ($this->isEmpty($value)) {
287 1
            if ($this->timestampAttribute !== null) {
288 1
                $model->{$this->timestampAttribute} = null;
289
            }
290 1
            return;
291
        }
292
293 168
        $timestamp = $this->parseDateValue($value);
294 168
        if ($timestamp === false) {
295 28
            if ($this->timestampAttribute === $attribute) {
296 1
                if ($this->timestampAttributeFormat === null) {
297 1
                    if (is_int($value)) {
298 1
                        return;
299
                    }
300 1
                } elseif ($this->parseDateValueFormat($value, $this->timestampAttributeFormat) !== false) {
301 1
                    return;
302
                }
303
            }
304 28
            $this->addError($model, $attribute, $this->message, []);
305 152
        } elseif ($this->min !== null && $timestamp < $this->min) {
306 3
            $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->minString]);
307 151
        } elseif ($this->max !== null && $timestamp > $this->max) {
308 2
            $this->addError($model, $attribute, $this->tooBig, ['max' => $this->maxString]);
309 151
        } elseif ($this->timestampAttribute !== null) {
310 139
            if ($this->timestampAttributeFormat === null) {
311 46
                $model->{$this->timestampAttribute} = $timestamp;
312
            } else {
313 108
                $model->{$this->timestampAttribute} = $this->formatTimestamp($timestamp, $this->timestampAttributeFormat);
314
            }
315
        }
316
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321 12
    protected function validateValue($value)
322
    {
323 12
        $timestamp = $this->parseDateValue($value);
324 12
        if ($timestamp === false) {
325 9
            return [$this->message, []];
326 12
        } elseif ($this->min !== null && $timestamp < $this->min) {
327 3
            return [$this->tooSmall, ['min' => $this->minString]];
328 11
        } elseif ($this->max !== null && $timestamp > $this->max) {
329 2
            return [$this->tooBig, ['max' => $this->maxString]];
330
        }
331
332 11
        return null;
333
    }
334
335
    /**
336
     * Parses date string into UNIX timestamp.
337
     *
338
     * @param mixed $value string representing date
339
     * @return int|false a UNIX timestamp or `false` on failure.
340
     */
341 177
    protected function parseDateValue($value)
342
    {
343
        // TODO consider merging these methods into single one at 2.1
344 177
        return $this->parseDateValueFormat($value, $this->format);
345
    }
346
347
    /**
348
     * Parses date string into UNIX timestamp.
349
     *
350
     * @param mixed $value string representing date
351
     * @param string $format expected date format
352
     * @return int|false a UNIX timestamp or `false` on failure.
353
     * @throws InvalidConfigException
354
     */
355 177
    private function parseDateValueFormat($value, $format)
356
    {
357 177
        if (is_array($value)) {
358 12
            return false;
359
        }
360 177
        if (strncmp($format, 'php:', 4) === 0) {
361 33
            $format = substr($format, 4);
362
        } else {
363 159
            if (extension_loaded('intl')) {
364 159
                return $this->parseDateValueIntl($value, $format);
365
            }
366
367
            // fallback to PHP if intl is not installed
368
            $format = FormatConverter::convertDateIcuToPhp($format, 'date');
369
        }
370
371 33
        return $this->parseDateValuePHP($value, $format);
372
    }
373
374
    /**
375
     * Parses a date value using the IntlDateFormatter::parse().
376
     * @param string $value string representing date
377
     * @param string $format the expected date format
378
     * @return int|bool a UNIX timestamp or `false` on failure.
379
     * @throws InvalidConfigException
380
     */
381 159
    private function parseDateValueIntl($value, $format)
382
    {
383 159
        $formatter = $this->getIntlDateFormatter($format);
384
        // enable strict parsing to avoid getting invalid date values
385 159
        $formatter->setLenient(false);
386
387
        // There should not be a warning thrown by parse() but this seems to be the case on windows so we suppress it here
388
        // See https://github.com/yiisoft/yii2/issues/5962 and https://bugs.php.net/bug.php?id=68528
389 159
        $parsePos = 0;
390 159
        $parsedDate = @$formatter->parse($value, $parsePos);
391 159
        $valueLength = mb_strlen($value, Yii::$app ? Yii::$app->charset : 'UTF-8');
392 159
        if ($parsedDate === false || $parsePos !== $valueLength || ($this->strictDateFormat && $formatter->format($parsedDate) !== $value)) {
393 23
            return false;
394
        }
395
396 151
        return $parsedDate;
397
    }
398
399
    /**
400
     * Creates IntlDateFormatter
401
     *
402
     * @param $format string date format
403
     * @return IntlDateFormatter
404
     * @throws InvalidConfigException
405
     */
406 159
    private function getIntlDateFormatter($format)
407
    {
408 159
        if (!isset($this->_dateFormats[$format])) {
409
            // if no time was provided in the format string set timezone to default one to match yii\i18n\Formatter::formatDateTimeValue()
410 159
            $timezone = strpbrk($format, 'ahHkKmsSA') !== false ? $this->timeZone : $this->defaultTimeZone;
411 159
            return new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $timezone, null, $format);
412
        }
413
414 6
        if ($this->type === self::TYPE_DATE) {
415 3
            $dateType = $this->_dateFormats[$format];
416 3
            $timeType = IntlDateFormatter::NONE;
417 3
            $timeZone = $this->defaultTimeZone;
418 3
        } elseif ($this->type === self::TYPE_DATETIME) {
419 3
            $dateType = $this->_dateFormats[$format];
420 3
            $timeType = $this->_dateFormats[$format];
421 3
            $timeZone = $this->timeZone;
422
        } elseif ($this->type === self::TYPE_TIME) {
423
            $dateType = IntlDateFormatter::NONE;
424
            $timeType = $this->_dateFormats[$format];
425
            $timeZone = $this->timeZone;
426
        } else {
427
            throw new InvalidConfigException('Unknown validation type set for DateValidator::$type: ' . $this->type);
428
        }
429
430 6
        return new IntlDateFormatter($this->locale, $dateType, $timeType, $timeZone);
431
    }
432
433
    /**
434
     * Parses a date value using the DateTime::createFromFormat().
435
     * @param string $value string representing date
436
     * @param string $format the expected date format
437
     * @return int|bool a UNIX timestamp or `false` on failure.
438
     */
439 33
    private function parseDateValuePHP($value, $format)
440
    {
441 33
        $hasTimeInfo = strpbrk($format, 'HhGgisU') !== false;
442
        // if no time was provided in the format string set timezone to default one to match yii\i18n\Formatter::formatDateTimeValue()
443 33
        $timezone = $hasTimeInfo ? $this->timeZone : $this->defaultTimeZone;
444 33
        $date = DateTime::createFromFormat($format, $value, new DateTimeZone($timezone));
445 33
        $errors = DateTime::getLastErrors(); // Before PHP 8.2 may return array instead of false (see https://github.com/php/php-src/issues/9431).
446 33
        if ($date === false || ($errors !== false && ($errors['error_count'] || $errors['warning_count'])) || ($this->strictDateFormat && $date->format($format) !== $value)) {
447 20
            return false;
448
        }
449
450 26
        if (!$hasTimeInfo) {
451
            // if no time was provided in the format string set time to 0 to get a simple date timestamp
452 22
            $date->setTime(0, 0, 0);
453
        }
454
455 26
        return $date->getTimestamp();
456
    }
457
458
    /**
459
     * Formats a timestamp using the specified format.
460
     * @param int $timestamp
461
     * @param string $format
462
     * @return string
463
     * @throws Exception
464
     */
465 108
    private function formatTimestamp($timestamp, $format)
466
    {
467 108
        if (strncmp($format, 'php:', 4) === 0) {
468 63
            $format = substr($format, 4);
469
        } else {
470 54
            $format = FormatConverter::convertDateIcuToPhp($format, 'date');
471
        }
472
473 108
        $date = new DateTime();
474 108
        $date->setTimestamp($timestamp);
475 108
        $date->setTimezone(new DateTimeZone($this->timestampAttributeTimeZone));
476
477 108
        return $date->format($format);
478
    }
479
}
480