Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

431 linhas
19KB

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