MongoDateValidatorTest.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace yiiunit\extensions\mongodb\validators;
  3. use MongoDB\BSON\UTCDateTime;
  4. use yii\base\Model;
  5. use yii\mongodb\validators\MongoDateValidator;
  6. use yiiunit\extensions\mongodb\TestCase;
  7. class MongoDateValidatorTest extends TestCase
  8. {
  9. protected function setUp()
  10. {
  11. parent::setUp();
  12. $this->mockApplication();
  13. date_default_timezone_set('UTC');
  14. }
  15. public function testValidateValue()
  16. {
  17. $validator = new MongoDateValidator();
  18. $this->assertFalse($validator->validate('string'));
  19. $this->assertTrue($validator->validate(new UTCDateTime(time() * 1000)));
  20. }
  21. public function testValidateAttribute()
  22. {
  23. $model = new MongoDateTestModel();
  24. $model->date = 'string';
  25. $this->assertFalse($model->validate());
  26. $model->date = new UTCDateTime(time() * 1000);
  27. $this->assertTrue($model->validate());
  28. }
  29. public function testMongoDateAttribute()
  30. {
  31. $model = new MongoDateTestModel();
  32. $model->date = '05/08/2015';
  33. $this->assertTrue($model->validate());
  34. $this->assertTrue($model->mongoDate instanceof UTCDateTime);
  35. $this->assertEquals('2015-05-08', $model->mongoDate->toDateTime()->format('Y-m-d'));
  36. $model->date = $model->mongoDate;
  37. $this->assertTrue($model->validate());
  38. $this->assertEquals('2015-05-08', $model->mongoDate->toDateTime()->format('Y-m-d'));
  39. }
  40. }
  41. class MongoDateTestModel extends Model
  42. {
  43. public $date;
  44. public $mongoDate;
  45. public function rules()
  46. {
  47. return [
  48. ['date', MongoDateValidator::className(), 'format' => 'MM/dd/yyyy', 'mongoDateAttribute' => 'mongoDate']
  49. ];
  50. }
  51. }