Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

424 lines
18KB

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