Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function getRoles() on user entity #186

Merged
merged 1 commit into from
Apr 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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