MongoDateValidator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\mongodb\validators;
  8. use MongoDB\BSON\UTCDateTime;
  9. use yii\validators\DateValidator;
  10. /**
  11. * MongoDateValidator is an enhanced version of [[DateValidator]], which supports [[\MongoDate]] values.
  12. *
  13. * Usage example:
  14. *
  15. * ```php
  16. * class Customer extends yii\mongodb\ActiveRecord
  17. * {
  18. * ...
  19. * public function rules()
  20. * {
  21. * return [
  22. * ['date', 'yii\mongodb\validators\MongoDateValidator', 'format' => 'MM/dd/yyyy']
  23. * ];
  24. * }
  25. * }
  26. * ```
  27. *
  28. * @see DateValidator
  29. *
  30. * @author Paul Klimov <klimov.paul@gmail.com>
  31. * @since 2.0.4
  32. */
  33. class MongoDateValidator extends DateValidator
  34. {
  35. /**
  36. * @var string the name of the attribute to receive the parsing result as [[\MongoDate]] instance.
  37. * When this property is not null and the validation is successful, the named attribute will
  38. * receive the parsing result as [[\MongoDate]] instance.
  39. *
  40. * This can be the same attribute as the one being validated. If this is the case,
  41. * the original value will be overwritten with the value after successful validation.
  42. */
  43. public $mongoDateAttribute;
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function validateAttribute($model, $attribute)
  48. {
  49. $mongoDateAttribute = $this->mongoDateAttribute;
  50. if ($this->timestampAttribute === null) {
  51. $this->timestampAttribute = $mongoDateAttribute;
  52. }
  53. $originalErrorCount = count($model->getErrors($attribute));
  54. parent::validateAttribute($model, $attribute);
  55. $afterValidateErrorCount = count($model->getErrors($attribute));
  56. if ($originalErrorCount === $afterValidateErrorCount) {
  57. if ($this->mongoDateAttribute !== null) {
  58. $timestamp = $model->{$this->timestampAttribute};
  59. $mongoDateAttributeValue = $model->{$this->mongoDateAttribute};
  60. // ensure "dirty attributes" support :
  61. if (!($mongoDateAttributeValue instanceof UTCDateTime) || $mongoDateAttributeValue->sec !== $timestamp) {
  62. $model->{$this->mongoDateAttribute} = new UTCDateTime($timestamp * 1000);
  63. }
  64. }
  65. }
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. protected function parseDateValue($value)
  71. {
  72. return $value instanceof UTCDateTime
  73. ? $value->toDateTime()->getTimestamp()
  74. : parent::parseDateValue($value);
  75. }
  76. }