Browse Source

Add numeric age attribute for user model

pull/27/head
Nafies Luthfi 7 years ago
parent
commit
20cf6e0794
  1. 24
      app/User.php
  2. 33
      tests/Unit/UserTest.php

24
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;

33
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)

Loading…
Cancel
Save