Completed
Push — 2.1 ( c952e8...98ed49 )
by Carsten
10:00
created

DateValidator::init()   F

Complexity

Conditions 20
Paths 3586

Size

Total Lines 50
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 20.5137

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 50
ccs 41
cts 46
cp 0.8913
rs 2.7628
cc 20
eloc 35
nc 3586
nop 0
crap 20.5137

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
     * @see timestampAttributeFormat
127
     * @see timestampAttributeTimeZone
128
     */
129
    public $timestampAttribute;
130
    /**
131
     * @var string the format to use when populating the [[timestampAttribute]].
132
     * The format can be specified in the same way as for [[format]].
133
     *
134
     * If not set, [[timestampAttribute]] will receive a UNIX timestamp.
135
     * If [[timestampAttribute]] is not set, this property will be ignored.
136
     * @see format
137
     * @see timestampAttribute
138
     * @since 2.0.4
139
     */
140
    public $timestampAttributeFormat;
141
    /**
142
     * @var string the timezone to use when populating the [[timestampAttribute]]. Defaults to `UTC`.
143
     *
144
     * 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)
145
     * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
146
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
147
     *
148
     * If [[timestampAttributeFormat]] is not set, this property will be ignored.
149
     * @see timestampAttributeFormat
150
     * @since 2.0.4
151
     */
152
    public $timestampAttributeTimeZone = 'UTC';
153
    /**
154
     * @var integer|string upper limit of the date. Defaults to null, meaning no upper limit.
155
     * This can be a unix timestamp or a string representing a date time value.
156
     * If this property is a string, [[format]] will be used to parse it.
157
     * @see tooBig for the customized message used when the date is too big.
158
     * @since 2.0.4
159
     */
160
    public $max;
161
    /**
162
     * @var integer|string lower limit of the date. Defaults to null, meaning no lower limit.
163
     * This can be a unix timestamp or a string representing a date time value.
164
     * If this property is a string, [[format]] will be used to parse it.
165
     * @see tooSmall for the customized message used when the date is too small.
166
     * @since 2.0.4
167
     */
168
    public $min;
169
    /**
170
     * @var string user-defined error message used when the value is bigger than [[max]].
171
     * @since 2.0.4
172
     */
173
    public $tooBig;
174
    /**
175
     * @var string user-defined error message used when the value is smaller than [[min]].
176
     * @since 2.0.4
177
     */
178
    public $tooSmall;
179
    /**
180
     * @var string user friendly value of upper limit to display in the error message.
181
     * If this property is null, the value of [[max]] will be used (before parsing).
182
     * @since 2.0.4
183
     */
184
    public $maxString;
185
    /**
186
     * @var string user friendly value of lower limit to display in the error message.
187
     * If this property is null, the value of [[min]] will be used (before parsing).
188
     * @since 2.0.4
189
     */
190
    public $minString;
191
192
    /**
193
     * @var array map of short format names to IntlDateFormatter constant values.
194
     */
195
    private $_dateFormats = [
196
        'short'  => 3, // IntlDateFormatter::SHORT,
197
        'medium' => 2, // IntlDateFormatter::MEDIUM,
198
        'long'   => 1, // IntlDateFormatter::LONG,
199
        'full'   => 0, // IntlDateFormatter::FULL,
200
    ];
201
202
203
    /**
204
     * @inheritdoc
205
     */
206 145
    public function init()
207
    {
208 145
        parent::init();
209 145
        if ($this->message === null) {
210 145
            $this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
211 145
        }
212 145
        if ($this->format === null) {
213 7
            if ($this->type === self::TYPE_DATE) {
214 4
                $this->format = Yii::$app->formatter->dateFormat;
215 7
            } elseif ($this->type === self::TYPE_DATETIME) {
216 3
                $this->format = Yii::$app->formatter->datetimeFormat;
217 3
            } elseif ($this->type === self::TYPE_TIME) {
218
                $this->format = Yii::$app->formatter->timeFormat;
219
            } else {
220
                throw new InvalidConfigException('Unknown validation type set for DateValidator::$type: ' . $this->type);
221
            }
222 7
        }
223 145
        if ($this->locale === null) {
224 144
            $this->locale = Yii::$app->language;
225 144
        }
226 145
        if ($this->timeZone === null) {
227 28
            $this->timeZone = Yii::$app->timeZone;
228 28
        }
229 145
        if ($this->min !== null && $this->tooSmall === null) {
230 4
            $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
231 4
        }
232 145
        if ($this->max !== null && $this->tooBig === null) {
233 4
            $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
234 4
        }
235 145
        if ($this->maxString === null) {
236 145
            $this->maxString = (string) $this->max;
237 145
        }
238 145
        if ($this->minString === null) {
239 145
            $this->minString = (string) $this->min;
240 145
        }
241 145
        if ($this->max !== null && is_string($this->max)) {
242 4
            $timestamp = $this->parseDateValue($this->max);
243 4
            if ($timestamp === false) {
244
                throw new InvalidConfigException("Invalid max date value: {$this->max}");
245
            }
246 4
            $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...
247 4
        }
248 145
        if ($this->min !== null && is_string($this->min)) {
249 4
            $timestamp = $this->parseDateValue($this->min);
250 4
            if ($timestamp === false) {
251
                throw new InvalidConfigException("Invalid min date value: {$this->min}");
252
            }
253 4
            $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...
254 4
        }
255 145
    }
256
257
    /**
258
     * @inheritdoc
259
     */
260 136
    public function validateAttribute($model, $attribute)
261
    {
262 136
        $value = $model->$attribute;
263 136
        $timestamp = $this->parseDateValue($value);
264 136
        if ($timestamp === false) {
265 13
            if ($this->timestampAttribute === $attribute) {
266 1
                if ($this->timestampAttributeFormat === null) {
267 1
                    if (is_int($value)) {
268 1
                        return;
269
                    }
270 1
                } else {
271 1
                    if ($this->parseDateValueFormat($value, $this->timestampAttributeFormat) !== false) {
272 1
                        return;
273
                    }
274
                }
275 1
            }
276 13
            $this->addError($model, $attribute, $this->message, []);
277 136
        } elseif ($this->min !== null && $timestamp < $this->min) {
278 2
            $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->minString]);
279 135
        } elseif ($this->max !== null && $timestamp > $this->max) {
280 2
            $this->addError($model, $attribute, $this->tooBig, ['max' => $this->maxString]);
281 135
        } elseif ($this->timestampAttribute !== null) {
282 132
            if ($this->timestampAttributeFormat === null) {
283 39
                $model->{$this->timestampAttribute} = $timestamp;
284 39
            } else {
285 102
                $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 263 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...
286
            }
287 132
        }
288 136
    }
289
290
    /**
291
     * @inheritdoc
292
     */
293 11
    protected function validateValue($value)
294
    {
295 11
        $timestamp = $this->parseDateValue($value);
296 11
        if ($timestamp === false) {
297 9
            return [$this->message, []];
298 11
        } elseif ($this->min !== null && $timestamp < $this->min) {
299 2
            return [$this->tooSmall, ['min' => $this->minString]];
300 11
        } elseif ($this->max !== null && $timestamp > $this->max) {
301 2
            return [$this->tooBig, ['max' => $this->maxString]];
302
        } else {
303 11
            return null;
304
        }
305
    }
306
307
    /**
308
     * Parses date string into UNIX timestamp
309
     *
310
     * @param string $value string representing date
311
     * @return integer|false a UNIX timestamp or `false` on failure.
312
     */
313 144
    protected function parseDateValue($value)
314
    {
315
        // TODO consider merging these methods into single one at 2.1
316 144
        return $this->parseDateValueFormat($value, $this->format);
317
    }
318
319
    /**
320
     * Parses date string into UNIX timestamp
321
     *
322
     * @param string $value string representing date
323
     * @param string $format expected date format
324
     * @return integer|false a UNIX timestamp or `false` on failure.
325
     */
326 144
    private function parseDateValueFormat($value, $format)
327
    {
328 144
        if (is_array($value)) {
329 12
            return false;
330
        }
331 144
        if (strncmp($format, 'php:', 4) === 0) {
332 16
            $format = substr($format, 4);
333 16
        } else {
334 137
            if (extension_loaded('intl')) {
335 69
                return $this->parseDateValueIntl($value, $format);
336
            } else {
337
                // fallback to PHP if intl is not installed
338 68
                $format = FormatConverter::convertDateIcuToPhp($format, 'date');
339
            }
340
        }
341 78
        return $this->parseDateValuePHP($value, $format);
342
    }
343
344
    /**
345
     * Parses a date value using the IntlDateFormatter::parse()
346
     * @param string $value string representing date
347
     * @param string $format the expected date format
348
     * @return integer|boolean a UNIX timestamp or `false` on failure.
349
     */
350 69
    private function parseDateValueIntl($value, $format)
351
    {
352 69
        if (isset($this->_dateFormats[$format])) {
353 6
            if ($this->type === self::TYPE_DATE) {
354 3
                $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, 'UTC');
355 6
            } elseif ($this->type === self::TYPE_DATETIME) {
356 3
                $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
357 3
            } elseif ($this->type === self::TYPE_TIME) {
358
                $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
359
            } else {
360
                throw new InvalidConfigException('Unknown validation type set for DateValidator::$type: ' . $this->type);
361
            }
362 6
        } else {
363
            // if no time was provided in the format string set time to 0 to get a simple date timestamp
364 69
            $hasTimeInfo = (strpbrk($format, 'ahHkKmsSA') !== false);
365 69
            $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $hasTimeInfo ? $this->timeZone : 'UTC', null, $format);
366
        }
367
        // enable strict parsing to avoid getting invalid date values
368 69
        $formatter->setLenient(false);
369
370
        // There should not be a warning thrown by parse() but this seems to be the case on windows so we suppress it here
371
        // See https://github.com/yiisoft/yii2/issues/5962 and https://bugs.php.net/bug.php?id=68528
372 69
        $parsePos = 0;
373 69
        $parsedDate = @$formatter->parse($value, $parsePos);
374 69
        if ($parsedDate === false || $parsePos !== mb_strlen($value, Yii::$app ? Yii::$app->charset : 'UTF-8')) {
375 9
            return false;
376 15
        }
377
378 69
        return $parsedDate;
379
    }
380
381
    /**
382
     * Parses a date value using the DateTime::createFromFormat()
383
     * @param string $value string representing date
384
     * @param string $format the expected date format
385
     * @return integer|boolean a UNIX timestamp or `false` on failure.
386
     */
387 78
    private function parseDateValuePHP($value, $format)
388
    {
389
        // if no time was provided in the format string set time to 0 to get a simple date timestamp
390 78
        $hasTimeInfo = (strpbrk($format, 'HhGgis') !== false);
391
392 78
        $date = DateTime::createFromFormat($format, $value, new \DateTimeZone($hasTimeInfo ? $this->timeZone : 'UTC'));
393 78
        $errors = DateTime::getLastErrors();
394 78
        if ($date === false || $errors['error_count'] || $errors['warning_count']) {
395 16
            return false;
396
        }
397
398 78
        if (!$hasTimeInfo) {
399 72
            $date->setTime(0, 0, 0);
400 72
        }
401 78
        return $date->getTimestamp();
402
    }
403
404
    /**
405
     * Formats a timestamp using the specified format
406
     * @param integer $timestamp
407
     * @param string $format
408
     * @return string
409
     */
410 102
    private function formatTimestamp($timestamp, $format)
411
    {
412 102
        if (strncmp($format, 'php:', 4) === 0) {
413 63
            $format = substr($format, 4);
414 63
        } else {
415 48
            $format = FormatConverter::convertDateIcuToPhp($format, 'date');
416
        }
417
418 102
        $date = new DateTime();
419 102
        $date->setTimestamp($timestamp);
420 102
        $date->setTimezone(new \DateTimeZone($this->timestampAttributeTimeZone));
421 102
        return $date->format($format);
422
    }
423
}
424