DatabaseSoftDeletingTest.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Illuminate\Tests\Database;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\SoftDeletes;
  5. use Illuminate\Support\Carbon;
  6. use PHPUnit\Framework\TestCase;
  7. class DatabaseSoftDeletingTest extends TestCase
  8. {
  9. public function testDeletedAtIsAddedToCastsAsDefaultType()
  10. {
  11. $model = new SoftDeletingModel;
  12. $this->assertArrayHasKey('deleted_at', $model->getCasts());
  13. $this->assertSame('datetime', $model->getCasts()['deleted_at']);
  14. }
  15. public function testDeletedAtIsCastToCarbonInstance()
  16. {
  17. Carbon::setTestNow(Carbon::now());
  18. $expected = Carbon::createFromFormat('Y-m-d H:i:s', '2018-12-29 13:59:39');
  19. $model = new SoftDeletingModel(['deleted_at' => $expected->format('Y-m-d H:i:s')]);
  20. $this->assertInstanceOf(Carbon::class, $model->deleted_at);
  21. $this->assertTrue($expected->eq($model->deleted_at));
  22. }
  23. public function testExistingCastOverridesAddedDateCast()
  24. {
  25. $model = new class(['deleted_at' => '2018-12-29 13:59:39']) extends SoftDeletingModel
  26. {
  27. protected $casts = ['deleted_at' => 'bool'];
  28. };
  29. $this->assertTrue($model->deleted_at);
  30. }
  31. public function testExistingMutatorOverridesAddedDateCast()
  32. {
  33. $model = new class(['deleted_at' => '2018-12-29 13:59:39']) extends SoftDeletingModel
  34. {
  35. protected function getDeletedAtAttribute()
  36. {
  37. return 'expected';
  38. }
  39. };
  40. $this->assertSame('expected', $model->deleted_at);
  41. }
  42. public function testCastingToStringOverridesAutomaticDateCastingToRetainPreviousBehaviour()
  43. {
  44. $model = new class(['deleted_at' => '2018-12-29 13:59:39']) extends SoftDeletingModel
  45. {
  46. protected $casts = ['deleted_at' => 'string'];
  47. };
  48. $this->assertSame('2018-12-29 13:59:39', $model->deleted_at);
  49. }
  50. }
  51. class SoftDeletingModel extends Model
  52. {
  53. use SoftDeletes;
  54. protected $guarded = [];
  55. protected $dateFormat = 'Y-m-d H:i:s';
  56. }