Skip to content

Instantly share code, notes, and snippets.

@omarkdev
Created December 16, 2016 12:27
Show Gist options
  • Save omarkdev/2140a5c623c4e1a338d72c307ce16bcc to your computer and use it in GitHub Desktop.
Save omarkdev/2140a5c623c4e1a338d72c307ce16bcc to your computer and use it in GitHub Desktop.
<?php
namespace Smart\Traits\Models;
trait RoleTrait {
/**
* Roles existed in application
*
* @var
*/
protected $configRoles;
/**
* Return the user role
*
* @return mixed
*/
protected function getUserRole()
{
return $this->attributes['role'];
}
/**
* Check if user role is equal parameter
*
* @param $roleHunch
*
* @return bool
*/
public function roleIs($roleHunch)
{
$role = $this->getInfoUserRole();
return $role['alias'] == $roleHunch;
}
/**
* Set the role correctly when set
*
* @param $value
*
* @return int|string
*/
public function setRoleAttribute($value)
{
if(is_numeric($value))
return $this->attributes['role'] = $value;
$role = $this->findInfoRole('alias', $value, true);
return $this->attributes['role'] = $role;
}
/**
* Find roles info
*
* @param $attribute
* @param $value
* @param bool $returnCod
*
* @return int|string
*/
private function findInfoRole($attribute, $value, $returnCod = false)
{
$roles = $this->getRoles();
foreach($roles as $cod => $role){
if(!isset($role[$attribute]) || $role[$attribute] != $value)
continue;
return ($returnCod === false) ? $role : $cod;
}
return $value;
}
/**
* Return roles existed in application
*
* @return mixed
*/
private function getRoles()
{
if(count($this->configRoles) === 0)
$this->configRoles = config('roles');
return $this->configRoles;
}
/**
* Return info role
*
* @param $role
*
* @return null
*/
private function getInfoRole($role)
{
$roles = $this->getRoles();
return (isset($roles[$role])) ? $roles[$role] : null;
}
/**
* Return info user role
*
* @return null
*/
private function getInfoUserRole()
{
$userRole = $this->getUserRole();
return $this->getInfoRole($userRole);
}
/**
* Return name of info user role
*
* @return mixed
*/
public function getRoleNameAttribute()
{
$role = $this->getInfoUserRole();
return $role['name'];
}
/**
* Return the class of info user role
*
* @return string
*/
public function getRoleClassAttribute()
{
$role = $this->getInfoUserRole();
return (isset($role['class'])) ? $role['class'] : 'primary';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment