Skip to content

Commit

Permalink
Merge pull request #186 from agungsugiarto/develop
Browse files Browse the repository at this point in the history
Add function getRoles() on user entity
  • Loading branch information
lonnieezell authored Apr 12, 2020
2 parents dde0b09 + d86b300 commit 67adfc8
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/Entities/User.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php namespace Myth\Auth\Entities;

use CodeIgniter\Entity;
use Myth\Auth\Authentication\GroupModel;
use Myth\Auth\Authorization\PermissionModel;

class User extends Entity
Expand Down Expand Up @@ -37,6 +38,12 @@ class User extends Entity
*/
protected $permissions = [];

/**
* Per-user roles cache
* @var array
*/
protected $roles = [];

/**
* Automatically hashes the password when set.
*
Expand Down Expand Up @@ -225,6 +232,36 @@ public function getPermissions()
}

return $this->permissions;
}

/**
* Returns the user's roles, formatted for simple checking:
*
* [
* id => name,
* id => name,
* ]
*
* @return array|mixed
*/
public function getRoles()
{
if (empty($this->id))
{
throw new \RuntimeException('Users must be created before getting roles.');
}

if (empty($this->roles))
{
$groups = (new GroupModel())->getGroupsForUser($this->id);

foreach ($groups as $group)
{
$this->roles[$group['group_id']] = strtolower($group['name']);
}
}

return $this->roles;
}

/**
Expand Down

0 comments on commit 67adfc8

Please sign in to comment.