Completed
Push — readme-redesign ( e2fd40...17eb05 )
by Alexander
108:51 queued 68:52
created

DateValidator::init()   F

Complexity

Conditions 20
Paths 3586

Size

Total Lines 50
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 50
rs 2.7628
c 0
b 0
f 0
cc 20
eloc 35
nc 3586
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use DateTime;
11
use IntlDateFormatter;
12
use Yii;
13
use yii\base\InvalidConfigException;
14
use yii\helpers\FormatConverter;
15
16
/**
17
 * DateValidator verifies if the attribute represents a date, time or datetime in a proper [[format]].
18
 *
19
 * It can also parse internationalized dates in a specific [[locale]] like e.g. `12 мая 2014` when [[format]]
20
 * is configured to use a time pattern in ICU format.
21
 *
22
 * It is further possible to limit the date within a certain range using [[min]] and [[max]].
23
 *
24
 * Additional to validating the date it can also export the parsed timestamp as a machine readable format
25
 * which can be configured using [[timestampAttribute]]. For values that include time information (not date-only values)
26
 * also the time zone will be adjusted. The time zone of the input value is assumed to be the one specified by the [[timeZone]]
27
 * property and the target timeZone will be UTC when [[timestampAttributeFormat]] is `null` (exporting as UNIX timestamp)
28
 * or [[timestampAttributeTimeZone]] otherwise. If you want to avoid the time zone conversion, make sure that [[timeZone]] and
29
 * [[timestampAttributeTimeZone]] are the same.
30
 *
31
 * @author Qiang Xue <[email protected]>
32
 * @author Carsten Brandt <[email protected]>
33
 * @since 2.0
34
 */
35
class DateValidator extends Validator
36
{
37
    /**
38
     * Constant for specifying the validation [[type]] as a date value, used for validation with intl short format.
39
     * @since 2.0.8
40
     * @see type
41
     */
42
    const TYPE_DATE = 'date';
43
    /**
44
     * Constant for specifying the validation [[type]] as a datetime value, used for validation with intl short format.
45
     * @since 2.0.8
46
     * @see type
47
     */
48
    const TYPE_DATETIME = 'datetime';
49
    /**
50
     * Constant for specifying the validation [[type]] as a time value, used for validation with intl short format.
51
     * @since 2.0.8
52
     * @see type
53
     */
54
    const TYPE_TIME = 'time';
55
56
    /**
57
     * @var string the type of the validator. Indicates, whether a date, time or datetime value should be validated.
58
     * This property influences the default value of [[format]] and also sets the correct behavior when [[format]] is one of the intl
59
     * short formats, `short`, `medium`, `long`, or `full`.
60
     *
61
     * This is only effective when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
62
     *
63
     * This property can be set to the following values:
64
     *
65
     * - [[TYPE_DATE]] - (default) for validating date values only, that means only values that do not include a time range are valid.
66
     * - [[TYPE_DATETIME]] - for validating datetime values, that contain a date part as well as a time part.
67
     * - [[TYPE_TIME]] - for validating time values, that contain no date information.
68
     *
69
     * @since 2.0.8
70
     */
71
    public $type = self::TYPE_DATE;
72
    /**
73
     * @var string the date format that the value being validated should follow.
74
     * 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).
75
     *
76
     * Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the PHP Datetime class.
77
     * Please refer to <http://php.net/manual/en/datetime.createfromformat.php> on supported formats.
78
     *
79
     * If this property is not set, the default value will be obtained from `Yii::$app->formatter->dateFormat`, see [[\yii\i18n\Formatter::dateFormat]] for details.
80
     * Since version 2.0.8 the default value will be determined from different formats of the formatter class,
81
     * dependent on the value of [[type]]:
82
     *
83
     * - if type is [[TYPE_DATE]], the default value will be taken from [[\yii\i18n\Formatter::dateFormat]],
84
     * - if type is [[TYPE_DATETIME]], it will be taken from [[\yii\i18n\Formatter::datetimeFormat]],
85
     * - and if type is [[TYPE_TIME]], it will be [[\yii\i18n\Formatter::timeFormat]].
86
     *
87
     * Here are some example values:
88
     *
89
     * ```php
90
     * 'MM/dd/yyyy' // date in ICU format
91
     * 'php:m/d/Y' // the same date in PHP format
92
     * 'MM/dd/yyyy HH:mm' // not only dates but also times can be validated
93
     * ```
94
     *
95
     * **Note:** the underlying date parsers being used vary dependent on the format. If you use the ICU format and
96
     * the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed, the [IntlDateFormatter](http://php.net/manual/en/intldateformatter.parse.php)
97
     * is used to parse the input value. In all other cases the PHP [DateTime](http://php.net/manual/en/datetime.createfromformat.php) class
98
     * is used. The IntlDateFormatter has the advantage that it can parse international dates like `12. Mai 2015` or `12 мая 2014`, while the
99
     * PHP parser is limited to English only. The PHP parser however is more strict about the input format as it will not accept
100
     * `12.05.05` for the format `php:d.m.Y`, but the IntlDateFormatter will accept it for the format `dd.MM.yyyy`.
101
     * If you need to use the IntlDateFormatter you can avoid this problem by specifying a [[min|minimum date]].
102
     */
103
    public $format;
104
    /**
105
     * @var string the locale ID that is used to localize the date parsing.
106
     * This is only effective when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
107
     * If not set, the locale of the [[\yii\base\Application::formatter|formatter]] will be used.
108
     * See also [[\yii\i18n\Formatter::locale]].
109
     */
110
    public $locale;
111
    /**
112
     * @var string the timezone to use for parsing date and time values.
113
     * 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)
114
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
115
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
116
     * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
117
     */
118
    public $timeZone;
119
    /**
120
     * @var string the name of the attribute to receive the parsing result.
121
     * When this property is not null and the validation is successful, the named attribute will
122
     * receive the parsing result.
123
     *
124
     * This can be the same attribute as the one being validated. If this is the case,
125
     * the original value will be overwritten with the timestamp value after successful validation.
126
     *
127
     * Note, that when using this property, the input value will be converted to a unix timestamp,
128
     * which by definition is in UTC, so a conversion from the [[$timeZone|input time zone]] to UTC
129
     * will be performed. When defining [[$timestampAttributeFormat]] you can control the conversion by
130
     * setting [[$timestampAttributeTimeZone]] to a different value than `'UTC'`.
131
     *
132
     * @see timestampAttributeFormat
133
     * @see timestampAttributeTimeZone
134
     */
135
    public $timestampAttribute;
136
    /**
137
     * @var string the format to use when populating the [[timestampAttribute]].
138
     * The format can be specified in the same way as for [[format]].
139
     *
140
     * If not set, [[timestampAttribute]] will receive a UNIX timestamp.
141
     * If [[timestampAttribute]] is not set, this property will be ignored.
142
     * @see format
143
     * @see timestampAttribute
144
     * @since 2.0.4
145
     */
146
    public $timestampAttributeFormat;
147
    /**
148
     * @var string the timezone to use when populating the [[timestampAttribute]]. Defaults to `UTC`.
149
     *
150
     * 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)
151
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
152
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
153
     *
154
     * If [[timestampAttributeFormat]] is not set, this property will be ignored.
155
     * @see timestampAttributeFormat
156
     * @since 2.0.4
157
     */
158
    public $timestampAttributeTimeZone = 'UTC';
159
    /**
160
     * @var int|string upper limit of the date. Defaults to null, meaning no upper limit.
161
     * This can be a unix timestamp or a string representing a date time value.
162
     * If this property is a string, [[format]] will be used to parse it.
163
     * @see tooBig for the customized message used when the date is too big.
164
     * @since 2.0.4
165
     */
166
    public $max;
167
    /**
168
     * @var int|string lower limit of the date. Defaults to null, meaning no lower limit.
169
     * This can be a unix timestamp or a string representing a date time value.
170
     * If this property is a string, [[format]] will be used to parse it.
171
     * @see tooSmall for the customized message used when the date is too small.
172
     * @since 2.0.4
173
     */
174
    public $min;
175
    /**
176
     * @var string user-defined error message used when the value is bigger than [[max]].
177
     * @since 2.0.4
178
     */
179
    public $tooBig;
180
    /**
181
     * @var string user-defined error message used when the value is smaller than [[min]].
182
     * @since 2.0.4
183
     */
184
    public $tooSmall;
185
    /**
186
     * @var string user friendly value of upper limit to display in the error message.
187
     * If this property is null, the value of [[max]] will be used (before parsing).
188
     * @since 2.0.4
189
     */
190
    public $maxString;
191
    /**
192
     * @var string user friendly value of lower limit to display in the error message.
193
     * If this property is null, the value of [[min]] will be used (before parsing).
194
     * @since 2.0.4
195
     */
196
    public $minString;
197
198
    /**
199
     * @var array map of short format names to IntlDateFormatter constant values.
200
     */
201
    private $_dateFormats = [
202
        'short'  => 3, // IntlDateFormatter::SHORT,
203
        'medium' => 2, // IntlDateFormatter::MEDIUM,
204
        'long'   => 1, // IntlDateFormatter::LONG,
205
        'full'   => 0, // IntlDateFormatter::FULL,
206
    ];
207
208
209
    /**
210
     * @inheritdoc
211
     */
212
    public function init()
213
    {
214
        parent::init();
215
        if ($this->message === null) {
216
            $this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
217
        }
218
        if ($this->format === null) {
219
            if ($this->type === self::TYPE_DATE) {
220
                $this->format = Yii::$app->formatter->dateFormat;
221
            } elseif ($this->type === self::TYPE_DATETIME) {
222
                $this->format = Yii::$app->formatter->datetimeFormat;
223
            } elseif ($this->type === self::TYPE_TIME) {
224
                $this->format = Yii::$app->formatter->timeFormat;
225
            } else {
226
                throw new InvalidConfigException('Unknown validation type set for DateValidator::$type: ' . $this->type);
227
            }
228
        }
229
        if ($this->locale === null) {
230
            $this->locale = Yii::$app->language;
231
        }
232
        if ($this->timeZone === null) {
233
            $this->timeZone = Yii::$app->timeZone;
234
        }
235
        if ($this->min !== null && $this->tooSmall === null) {
236
            $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
237
        }
238
        if ($this->max !== null && $this->tooBig === null) {
239
            $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
240
        }
241
        if ($this->maxString === null) {
242
            $this->maxString = (string) $this->max;
243
        }
244
        if ($this->minString === null) {
245
            $this->minString = (string) $this->min;
246
        }
247
        if ($this->max !== null && is_string($this->max)) {
248
            $timestamp = $this->parseDateValue($this->max);
249
            if ($timestamp === false) {
250
                throw new InvalidConfigException("Invalid max date value: {$this->max}");
251
            }
252
            $this->max = $timestamp;
0 ignored issues
show
Documentation Bug introduced by
It seems like $timestamp can also be of type boolean. However, the property $max is declared as type integer|string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
253
        }
254
        if ($this->min !== null && is_string($this->min)) {
255
            $timestamp = $this->parseDateValue($this->min);
256
            if ($timestamp === false) {
257
                throw new InvalidConfigException("Invalid min date value: {$this->min}");
258
            }
259
            $this->min = $timestamp;
0 ignored issues
show
Documentation Bug introduced by
It seems like $timestamp can also be of type boolean. However, the property $min is declared as type integer|string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
260
        }
261
    }
262
263
    /**
264
     * @inheritdoc
265
     */
266
    public function validateAttribute($model, $attribute)
267
    {
268
        $value = $model->$attribute;
269
        $timestamp = $this->parseDateValue($value);
270
        if ($timestamp === false) {
271
            if ($this->timestampAttribute === $attribute) {
272
                if ($this->timestampAttributeFormat === null) {
273
                    if (is_int($value)) {
274
                        return;
275
                    }
276
                } else {
277
                    if ($this->parseDateValueFormat($value, $this->timestampAttributeFormat) !== false) {
278
                        return;
279
                    }
280
                }
281
            }
282
            $this->addError($model, $attribute, $this->message, []);
283
        } elseif ($this->min !== null && $timestamp < $this->min) {
284
            $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->minString]);
285
        } elseif ($this->max !== null && $timestamp > $this->max) {
286
            $this->addError($model, $attribute, $this->tooBig, ['max' => $this->maxString]);
287
        } elseif ($this->timestampAttribute !== null) {
288
            if ($this->timestampAttributeFormat === null) {
289
                $model->{$this->timestampAttribute} = $timestamp;
290
            } else {
291
                $model->{$this->timestampAttribute} = $this->formatTimestamp($timestamp, $this->timestampAttributeFormat);
0 ignored issues
show
Bug introduced by
It seems like $timestamp defined by $this->parseDateValue($value) on line 269 can also be of type boolean; however, yii\validators\DateValidator::formatTimestamp() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
292
            }
293
        }
294
    }
295
296
    /**
297
     * @inheritdoc
298
     */
299
    protected function validateValue($value)
300
    {
301
        $timestamp = $this->parseDateValue($value);
302
        if ($timestamp === false) {
303
            return [$this->message, []];
304
        } elseif ($this->min !== null && $timestamp < $this->min) {
305
            return [$this->tooSmall, ['min' => $this->minString]];
306
        } elseif ($this->max !== null && $timestamp > $this->max) {
307
            return [$this->tooBig, ['max' => $this->maxString]];
308
        } else {
309
            return null;
310
        }
311
    }
312
313
    /**
314
     * Parses date string into UNIX timestamp
315
     *
316
     * @param string $value string representing date
317
     * @return int|false a UNIX timestamp or `false` on failure.
318
     */
319
    protected function parseDateValue($value)
320
    {
321
        // TODO consider merging these methods into single one at 2.1
322
        return $this->parseDateValueFormat($value, $this->format);
323
    }
324
325
    /**
326
     * Parses date string into UNIX timestamp
327
     *
328
     * @param string $value string representing date
329
     * @param string $format expected date format
330
     * @return int|false a UNIX timestamp or `false` on failure.
331
     */
332
    private function parseDateValueFormat($value, $format)
333
    {
334
        if (is_array($value)) {
335
            return false;
336
        }
337
        if (strncmp($format, 'php:', 4) === 0) {
338
            $format = substr($format, 4);
339
        } else {
340
            if (extension_loaded('intl')) {
341
                return $this->parseDateValueIntl($value, $format);
342
            } else {
343
                // fallback to PHP if intl is not installed
344
                $format = FormatConverter::convertDateIcuToPhp($format, 'date');
345
            }
346
        }
347
        return $this->parseDateValuePHP($value, $format);
348
    }
349
350
    /**
351
     * Parses a date value using the IntlDateFormatter::parse()
352
     * @param string $value string representing date
353
     * @param string $format the expected date format
354
     * @return int|bool a UNIX timestamp or `false` on failure.
355
     * @throws InvalidConfigException
356
     */
357
    private function parseDateValueIntl($value, $format)
358
    {
359
        if (isset($this->_dateFormats[$format])) {
360
            if ($this->type === self::TYPE_DATE) {
361
                $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, 'UTC');
362
            } elseif ($this->type === self::TYPE_DATETIME) {
363
                $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
364
            } elseif ($this->type === self::TYPE_TIME) {
365
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
366
            } else {
367
                throw new InvalidConfigException('Unknown validation type set for DateValidator::$type: ' . $this->type);
368
            }
369
        } else {
370
            // if no time was provided in the format string set time to 0 to get a simple date timestamp
371
            $hasTimeInfo = (strpbrk($format, 'ahHkKmsSA') !== false);
372
            $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $hasTimeInfo ? $this->timeZone : 'UTC', null, $format);
373
        }
374
        // enable strict parsing to avoid getting invalid date values
375
        $formatter->setLenient(false);
376
377
        // There should not be a warning thrown by parse() but this seems to be the case on windows so we suppress it here
378
        // See https://github.com/yiisoft/yii2/issues/5962 and https://bugs.php.net/bug.php?id=68528
379
        $parsePos = 0;
380
        $parsedDate = @$formatter->parse($value, $parsePos);
381
        if ($parsedDate === false || $parsePos !== mb_strlen($value, Yii::$app ? Yii::$app->charset : 'UTF-8')) {
382
            return false;
383
        }
384
385
        return $parsedDate;
386
    }
387
388
    /**
389
     * Parses a date value using the DateTime::createFromFormat()
390
     * @param string $value string representing date
391
     * @param string $format the expected date format
392
     * @return int|bool a UNIX timestamp or `false` on failure.
393
     */
394
    private function parseDateValuePHP($value, $format)
395
    {
396
        // if no time was provided in the format string set time to 0 to get a simple date timestamp
397
        $hasTimeInfo = (strpbrk($format, 'HhGgis') !== false);
398
399
        $date = DateTime::createFromFormat($format, $value, new \DateTimeZone($hasTimeInfo ? $this->timeZone : 'UTC'));
400
        $errors = DateTime::getLastErrors();
401
        if ($date === false || $errors['error_count'] || $errors['warning_count']) {
402
            return false;
403
        }
404
405
        if (!$hasTimeInfo) {
406
            $date->setTime(0, 0, 0);
407
        }
408
        return $date->getTimestamp();
409
    }
410
411
    /**
412
     * Formats a timestamp using the specified format
413
     * @param int $timestamp
414
     * @param string $format
415
     * @return string
416
     */
417
    private function formatTimestamp($timestamp, $format)
418
    {
419
        if (strncmp($format, 'php:', 4) === 0) {
420
            $format = substr($format, 4);
421
        } else {
422
            $format = FormatConverter::convertDateIcuToPhp($format, 'date');
423
        }
424
425
        $date = new DateTime();
426
        $date->setTimestamp($timestamp);
427
        $date->setTimezone(new \DateTimeZone($this->timestampAttributeTimeZone));
428
        return $date->format($format);
429
    }
430
}
431