Browse Source

Add age attribute for user model

pull/27/head
Nafies Luthfi 7 years ago
parent
commit
cdde253fa9
  1. 14
      app/User.php
  2. 26
      tests/Unit/UserTest.php

14
app/User.php

@ -2,6 +2,7 @@
namespace App; namespace App;
use Carbon\Carbon;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
@ -230,4 +231,17 @@ class User extends Authenticatable
{ {
return $this->hasMany(Couple::class, 'manager_id'); 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;
}
} }

26
tests/Unit/UserTest.php

@ -4,6 +4,7 @@ namespace Tests\Unit;
use App\User; use App\User;
use App\Couple; use App\Couple;
use Carbon\Carbon;
use Tests\TestCase; use Tests\TestCase;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@ -145,4 +146,29 @@ class UserTest extends TestCase
$this->assertInstanceOf(Collection::class, $user->managedCouples); $this->assertInstanceOf(Collection::class, $user->managedCouples);
$this->assertInstanceOf(Couple::class, $user->managedCouples->first()); $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],
];
}
} }
Loading…
Cancel
Save