diff --git a/app/User.php b/app/User.php index f811a17..f852b21 100644 --- a/app/User.php +++ b/app/User.php @@ -2,6 +2,7 @@ namespace App; +use Carbon\Carbon; use Ramsey\Uuid\Uuid; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; @@ -230,4 +231,17 @@ class User extends Authenticatable { return $this->hasMany(Couple::class, 'manager_id'); } + + public function getAgeAttribute() + { + $age = null; + + if ($this->dob) { + $age = Carbon::parse($this->dob)->diffInYears($this->dod); + } elseif (!$this->dob && $this->yob) { + $age = date('Y') - $this->yob; + } + + return $age; + } } diff --git a/tests/Unit/UserTest.php b/tests/Unit/UserTest.php index 96c839d..17219bb 100644 --- a/tests/Unit/UserTest.php +++ b/tests/Unit/UserTest.php @@ -4,6 +4,7 @@ namespace Tests\Unit; use App\User; use App\Couple; +use Carbon\Carbon; use Tests\TestCase; use Illuminate\Support\Collection; use Illuminate\Foundation\Testing\RefreshDatabase; @@ -145,4 +146,29 @@ class UserTest extends TestCase $this->assertInstanceOf(Collection::class, $user->managedCouples); $this->assertInstanceOf(Couple::class, $user->managedCouples->first()); } + + /** + * @test + * @dataProvider userAgeDataProvider + */ + public function user_has_age_attribute($now, $dob, $yob, $dod, $yod, $age) + { + Carbon::setTestNow($now); + $user = factory(User::class)->make([ + 'dob' => $dob, 'yob' => $yob, 'dod' => $dod, 'yod' => $yod, + ]); + + $this->assertEquals($age, $user->age); + + Carbon::setTestNow(); + } + + 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], + ]; + } }