Skip to content

Commit

Permalink
Add can, cant and cannot methods to the Role model
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Jul 13, 2016
1 parent 5dfeb21 commit d1b1187
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 1 deletion.
57 changes: 57 additions & 0 deletions src/Database/Authorizable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Silber\Bouncer\Database;

use Silber\Bouncer\Clipboard;
use Illuminate\Container\Container;

trait Authorizable
{
/**
* Determine if the authority has a given ability.
*
* @param string $ability
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function can($ability, $model = null)
{
return $this->getClipboardInstance()->check($this, $ability, $model);
}

/**
* Determine if the authority does not have a given ability.
*
* @param string $ability
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function cant($ability, $model = null)
{
return ! $this->can($ability, $model);
}

/**
* Determine if the authority does not have a given ability.
*
* @param string $ability
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function cannot($ability, $model = null)
{
return $this->cant($ability, $model);
}

/**
* Get an instance of the bouncer's clipboard.
*
* @return \Silber\Bouncer\Clipboard
*/
protected function getClipboardInstance()
{
$container = Container::getInstance() ?: new Container;

return $container->make(Clipboard::class);
}
}
4 changes: 3 additions & 1 deletion src/Database/Role.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@

class Role extends Model
{
use HasAbilities;
use HasAbilities, Authorizable {
HasAbilities::getClipboardInstance insteadof Authorizable;
}

/**
* The attributes that are mass assignable.
Expand Down
17 changes: 17 additions & 0 deletions tests/AuthorizableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

use Silber\Bouncer\Database\Role;

class AuthorizableTest extends BaseTestCase
{
public function testCheckingAbilitiesOnRole()
{
$role = Role::create(['name' => 'admin']);

$role->allow('scream');

$this->assertTrue($role->can('scream'));
$this->assertTrue($role->cant('shout'));
$this->assertTrue($role->cannot('cry'));
}
}

0 comments on commit d1b1187

Please sign in to comment.