From 9e70f3154e0b49a2fb206b794edb9f0fc4422b32 Mon Sep 17 00:00:00 2001 From: Andrey Helldar Date: Wed, 25 Dec 2019 16:40:41 +0300 Subject: [PATCH] Added a new mutator cast type - `time` --- .../Eloquent/Concerns/HasAttributes.php | 15 ++++++ .../Database/EloquentModelTimeCastingTest.php | 47 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/Integration/Database/EloquentModelTimeCastingTest.php diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index d6ab699eed60..e6692a84bbae 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -508,6 +508,8 @@ protected function castAttribute($key, $value) case 'datetime': case 'custom_datetime': return $this->asDateTime($value); + case 'time': + return $this->asTime($value); case 'timestamp': return $this->asTimestamp($value); default: @@ -837,6 +839,19 @@ public function fromDateTime($value) ); } + /** + * Return a timestamp as DateTime object with the current date. + * + * @param mixed $value + * @return false|\Illuminate\Support\Carbon + */ + protected function asTime($value) + { + return $value instanceof CarbonInterface + ? Date::instance($value) + : Date::createFromFormat('H:i:s', $value)->startOfSecond(); + } + /** * Return a timestamp as unix timestamp. * diff --git a/tests/Integration/Database/EloquentModelTimeCastingTest.php b/tests/Integration/Database/EloquentModelTimeCastingTest.php new file mode 100644 index 000000000000..c51627f59b73 --- /dev/null +++ b/tests/Integration/Database/EloquentModelTimeCastingTest.php @@ -0,0 +1,47 @@ + '08:11:27', + ]); + + $this->assertEquals(date_create('08:11:27'), $item->time_field); + $this->assertEquals(date_create('08:11:27'), $item->toArray()['time_field']); + $this->assertSame('08:11:27', $item->time_field->format('H:i:s')); + $this->assertSame('08:11', $item->time_field->format('H:i')); + $this->assertInstanceOf(Carbon::class, $item->time_field); + } + + protected function setUp(): void + { + parent::setUp(); + + Schema::create('test_model1', function (Blueprint $table) { + $table->increments('id'); + $table->time('time_field')->nullable(); + }); + } +} + +class TestTimeModel extends Model +{ + public $timestamps = false; + + protected $table = 'test_model1'; + + protected $guarded = ['id']; + + protected $casts = [ + 'time_field' => 'time', + ]; +}