Last active
November 11, 2015 23:45
-
-
Save Keoghan/98d1791b21986b3da4b2 to your computer and use it in GitHub Desktop.
Trait to work with Silber Bouncer to add some role assignment helpers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Support\Str; | |
use Silber\Bouncer\Database\Role; | |
/** | |
* Trait AssignsRoles. | |
* Works with Silber\Bouncer to add some role assignment helpers | |
*/ | |
trait AssignsRoles | |
{ | |
/** | |
* Get a list of assignable roles | |
* | |
* @return mixed | |
*/ | |
public function assignableRoles() | |
{ | |
$roles = Role::all(); | |
$abilities = $this->getAbilities()->lists('name')->all(); | |
return $roles->reject(function($role) use ($abilities) { | |
if (! in_array($this->buildRoleAssignmentAbility($role->name), $abilities)) { | |
return true; | |
}; | |
}); | |
} | |
/** | |
* Check if a user can assign a role. | |
* @param $role \Silber\Bouncer\Database\Role|string|integer | |
* | |
* @return boolean | |
*/ | |
public function canAssignRole($role) | |
{ | |
$role = $this->getRoleName($role); | |
return $this->can($this->buildRoleAssignmentAbility($role)); | |
} | |
/** | |
* Determine role title | |
* @param $role \Silber\Bouncer\Database\Role|string|integer | |
* | |
* @return string | |
* @throws \RuntimeException | |
*/ | |
protected function getRoleName($role) | |
{ | |
if (is_string($role)) { | |
return $role; | |
} | |
if (is_integer($role)) { | |
return Role::find($role)->name; | |
} | |
if ($role instanceof Role) { | |
return $role->name; | |
} | |
throw new \RuntimeException('Unable to identify role.'); | |
} | |
/** | |
* Remove all roles from this user. | |
*/ | |
public function retractAll() | |
{ | |
$this->roles()->detach(); | |
} | |
/** | |
* Build the assignment ability string, used when checking abilities. | |
* | |
* @param $title string | |
* | |
* @return string | |
*/ | |
protected function buildRoleAssignmentAbility($name) | |
{ | |
return 'assign-' . Str::slug($name) . '-role'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment