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
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
B parseDateValuePHP() 0 17 9

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