|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Integration; |
| 4 | + |
| 5 | +use DateTime; |
| 6 | +use MongoDB\BSON\UTCDateTime; |
| 7 | +use Mongolid\Tests\Integration\IntegrationTestCase; |
| 8 | +use Mongolid\Tests\Stubs\ExpirablePrice; |
| 9 | +use Mongolid\Tests\Stubs\Legacy\LegacyRecordUser; |
| 10 | +use Mongolid\Util\LocalDateTime; |
| 11 | + |
| 12 | +class DateTimeCastTest extends IntegrationTestCase |
| 13 | +{ |
| 14 | + public function testShouldCreateAndSavePricesWithCastedAttributes(): void |
| 15 | + { |
| 16 | + // Set |
| 17 | + $price = new ExpirablePrice(); |
| 18 | + $price->value = '100.0'; |
| 19 | + $price->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2025'); |
| 20 | + |
| 21 | + // Actions |
| 22 | + $price->save(); |
| 23 | + |
| 24 | + // Assertions |
| 25 | + $this->assertInstanceOf(DateTime::class, $price->expires_at); |
| 26 | + $this->assertInstanceOf(UTCDateTime::class, $price->getOriginalDocumentAttributes()['expires_at']); |
| 27 | + |
| 28 | + $price = ExpirablePrice::first($price->_id); |
| 29 | + $this->assertSame('02/10/2025', $price->expires_at->format('d/m/Y')); |
| 30 | + $this->assertSame( |
| 31 | + '02/10/2025', |
| 32 | + LocalDateTime::get($price->getOriginalDocumentAttributes()['expires_at']) |
| 33 | + ->format('d/m/Y') |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + public function testShouldUpdatePriceWithCastedAttributes(): void |
| 38 | + { |
| 39 | + // Set |
| 40 | + $price = new ExpirablePrice(); |
| 41 | + $price->value = '100.0'; |
| 42 | + $price->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2025'); |
| 43 | + |
| 44 | + // Actions |
| 45 | + $price->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2030'); |
| 46 | + |
| 47 | + // Assertions |
| 48 | + $this->assertInstanceOf(DateTime::class, $price->expires_at); |
| 49 | + $this->assertSame('02/10/2030', $price->expires_at->format('d/m/Y')); |
| 50 | + } |
| 51 | + |
| 52 | + public function testShouldSaveAndReadLegacyRecordWithCastedAttibutes(): void |
| 53 | + { |
| 54 | + // Set |
| 55 | + $entity = new class extends LegacyRecordUser { |
| 56 | + protected array $casts = [ |
| 57 | + 'expires_at' => 'datetime', |
| 58 | + ]; |
| 59 | + }; |
| 60 | + $entity->expires_at = DateTime::createFromFormat('d/m/Y', '02/10/2025'); |
| 61 | + |
| 62 | + // Actions |
| 63 | + $entity->save(); |
| 64 | + |
| 65 | + // Assertions |
| 66 | + $this->assertInstanceOf(DateTime::class, $entity->expires_at); |
| 67 | + $this->assertInstanceOf(UTCDateTime::class, $entity->getOriginalDocumentAttributes()['expires_at']); |
| 68 | + } |
| 69 | +} |
0 commit comments