From 79173ee26931525757c19268c1a3580ddb2d64f8 Mon Sep 17 00:00:00 2001 From: Nafies Luthfi Date: Sat, 8 Jun 2019 08:10:00 +0800 Subject: [PATCH] Use timespan for age attribute --- app/User.php | 18 ++++++++++++++---- tests/Unit/UserTest.php | 18 +++++++++++++----- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/app/User.php b/app/User.php index f852b21..1205e80 100644 --- a/app/User.php +++ b/app/User.php @@ -236,10 +236,20 @@ class User extends Authenticatable { $age = null; - if ($this->dob) { - $age = Carbon::parse($this->dob)->diffInYears($this->dod); - } elseif (!$this->dob && $this->yob) { - $age = date('Y') - $this->yob; + if ($this->dob && !$this->dod) { + $age = Carbon::parse($this->dob)->timespan(); + } + if (!$this->dob && $this->yob) { + $age = (date('Y') - $this->yob).' tahun'; + } + if ($this->dob && $this->dod) { + $age = Carbon::parse($this->dob)->timespan($this->dod); + } + if (!$this->dob && $this->yob && !$this->dod && $this->yod) { + $age = ($this->yod - $this->yob).' tahun'; + } + if ($this->dob && $this->yob && $this->dod && $this->yod) { + $age = Carbon::parse($this->dob)->timespan($this->dod); } return $age; diff --git a/tests/Unit/UserTest.php b/tests/Unit/UserTest.php index 17219bb..bfa8286 100644 --- a/tests/Unit/UserTest.php +++ b/tests/Unit/UserTest.php @@ -151,9 +151,9 @@ class UserTest extends TestCase * @test * @dataProvider userAgeDataProvider */ - public function user_has_age_attribute($now, $dob, $yob, $dod, $yod, $age) + public function user_has_age_attribute($today, $dob, $yob, $dod, $yod, $age) { - Carbon::setTestNow($now); + Carbon::setTestNow($today); $user = factory(User::class)->make([ 'dob' => $dob, 'yob' => $yob, 'dod' => $dod, 'yod' => $yod, ]); @@ -163,12 +163,20 @@ class UserTest extends TestCase Carbon::setTestNow(); } + /** + * Provide data for calculating user age. + * Returning array of today, dob, yob, dod, yod, and age. + * + * @return array + */ public function userAgeDataProvider() { - // returning array of now, dob, yob, dod, yod, age. return [ - ['2018-02-02 01:00:00', '1997-01-01', '1997', null, null, 21], - ['2018-02-02 01:00:00', null, '1997', null, null, 22], + ['2018-02-02', '1997-01-01', '1997', null, null, '21 tahun, 1 bulan, 1 hari'], + ['2018-02-02', '1997-01-01', null, null, null, '21 tahun, 1 bulan, 1 hari'], + ['2018-02-02', null, '1997', null, null, '22 tahun'], + ['2018-02-02', '1997-01-01', '1997', '2017-01-01', '2017', '20 tahun'], + ['2018-02-02', null, '1997', null, '2017', '20 tahun'], ]; } }