From 20cf6e079438c031ba6c143ec4b5245c9bd3165a Mon Sep 17 00:00:00 2001 From: Nafies Luthfi Date: Sat, 8 Jun 2019 09:34:41 +0800 Subject: [PATCH] Add numeric age attribute for user model --- app/User.php | 24 ++++++++++++++++++++++++ tests/Unit/UserTest.php | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/app/User.php b/app/User.php index fb18e7a..aa24dcf 100644 --- a/app/User.php +++ b/app/User.php @@ -232,6 +232,30 @@ class User extends Authenticatable return $this->hasMany(Couple::class, 'manager_id'); } + public function getAgeAttribute() + { + $ageDetail = null; + $yearOnlySuffix = Carbon::now()->format('-m-d'); + + if ($this->dob && !$this->dod) { + $ageDetail = Carbon::parse($this->dob)->diffInYears(); + } + if (!$this->dob && $this->yob) { + $ageDetail = Carbon::parse($this->yob.$yearOnlySuffix)->diffInYears(); + } + if ($this->dob && $this->dod) { + $ageDetail = Carbon::parse($this->dob)->diffInYears($this->dod); + } + if (!$this->dob && $this->yob && !$this->dod && $this->yod) { + $ageDetail = Carbon::parse($this->yob.$yearOnlySuffix)->diffInYears($this->yod.$yearOnlySuffix); + } + if ($this->dob && $this->yob && $this->dod && $this->yod) { + $ageDetail = Carbon::parse($this->dob)->diffInYears($this->dod); + } + + return $ageDetail; + } + public function getAgeDetailAttribute() { $ageDetail = null; diff --git a/tests/Unit/UserTest.php b/tests/Unit/UserTest.php index 34b3e07..b2ce620 100644 --- a/tests/Unit/UserTest.php +++ b/tests/Unit/UserTest.php @@ -149,6 +149,39 @@ class UserTest extends TestCase /** * @test + * @dataProvider userAgeDataProvider + */ + public function user_has_age_attribute($today, $dob, $yob, $dod, $yod, $age) + { + Carbon::setTestNow($today); + $user = factory(User::class)->make([ + 'dob' => $dob, 'yob' => $yob, 'dod' => $dod, 'yod' => $yod, + ]); + + $this->assertEquals($age, $user->age); + + Carbon::setTestNow(); + } + + /** + * Provide data for calculating user age. + * Returning array of today, dob, yob, dod, yod, and age. + * + * @return array + */ + public function userAgeDataProvider() + { + return [ + ['2018-02-02', '1997-01-01', '1997', null, null, 21], + ['2018-02-02', '1997-01-01', null, null, null, 21], + ['2018-02-02', null, '1997', null, null, 21], + ['2018-02-02', '1997-01-01', '1997', '2017-01-01', '2017', 20], + ['2018-02-02', null, '1997', null, '2017', 20], + ]; + } + + /** + * @test * @dataProvider userAgeDetailDataProvider */ public function user_has_age_detail_attribute($today, $dob, $yob, $dod, $yod, $age)