Skip to content
This repository has been archived by the owner on May 19, 2020. It is now read-only.

Commit

Permalink
Add test and PermissionNotFound exception
Browse files Browse the repository at this point in the history
  • Loading branch information
kaidesu committed Aug 30, 2019
1 parent 53c7b9b commit d1a9874
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 10 deletions.
14 changes: 4 additions & 10 deletions src/Concerns/HasPermissions.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Caffeinated\Shinobi\Facades\Shinobi;
use Caffeinated\Shinobi\Contracts\Permission;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Caffeinated\Shinobi\Exceptions\PermissionNotFoundException;

trait HasPermissions
{
Expand Down Expand Up @@ -39,24 +40,17 @@ public function hasPermissionTo($permission): bool

// Fetch permission if we pass through a string
if (is_string($permission)) {
try {
$model = $this->getPermissionModel();

if(method_exists($model, 'firstOrFail'))
$permission = $model->where('slug', $permission)->firstOrFail();
else //If its cached
$permission = $model->where('slug', $permission)->first();

} catch (\Exception $e) {
$permission = $this->getPermissionModel()->where('slug', $permission)->first();

if (! $permission) {
throw new PermissionNotFoundException;
}
}

// Check role permissions
if (method_exists($this, 'hasPermissionThroughRole') and $this->hasPermissionThroughRole($permission)) {
return true;
}


// Check user permission
if ($this->hasPermission($permission)) {
Expand Down
10 changes: 10 additions & 0 deletions src/Exceptions/PermissionNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Caffeinated\Shinobi\Exceptions;

use Exception;

class PermissionNotFoundException extends Exception
{
//
}
19 changes: 19 additions & 0 deletions tests/PermissionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Caffeinated\Shinobi\Tests;

use Caffeinated\Shinobi\Tests\User;
use Caffeinated\Shinobi\Exceptions\PermissionNotFoundException;

class PermissionTest extends TestCase
{
/** @test */
public function a_non_existant_permission_should_throw_an_exception()
{
$this->expectException(PermissionNotFoundException::class);

$user = factory(User::class)->create();

$user->hasPermissionTo('i.dont.exist');
}
}

0 comments on commit d1a9874

Please sign in to comment.