DateValidator.php 20 KB

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