Skip to content

Commit

Permalink
Adding a PermissionAdder class providing access to add all permission…
Browse files Browse the repository at this point in the history
…s for given module name to the admin role (id:1)
  • Loading branch information
nWidart committed Oct 10, 2017
1 parent ad80d34 commit cfa3997
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 0 deletions.
55 changes: 55 additions & 0 deletions Modules/User/Permissions/PermissionsAdder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace Modules\User\Permissions;

use Modules\User\Repositories\RoleRepository;

final class PermissionsAdder
{
/**
* @var string
*/
private $moduleName;
/**
* @var RoleRepository
*/
private $role;

public function __construct($moduleName)
{
$this->moduleName = $moduleName;
$this->role = app(RoleRepository::class);
}

public function addAll()
{
$permissions = $this->buildPermissionList();

$role = $this->role->find(1);
foreach ($permissions as $permission) {
$role->addPermission($permission);
$role->save();
}
}

/**
* @return array
*/
private function buildPermissionList() : array
{
$permissionsConfig = config('asgard.' . strtolower($this->moduleName) . '.permissions');
$list = [];

if ($permissionsConfig === null) {
return $list;
}

foreach ($permissionsConfig as $mainKey => $subPermissions) {
foreach ($subPermissions as $key => $description) {
$list[] = $mainKey . '.' . $key;
}
}

return $list;
}
}
59 changes: 59 additions & 0 deletions Modules/User/Tests/Permissions/PermissionsAdderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Modules\User\Tests\Permissions;

use Modules\User\Permissions\PermissionsAdder;
use Modules\User\Repositories\RoleRepository;
use Modules\User\Repositories\UserRepository;
use Modules\User\Tests\BaseUserTestCase;

final class PermissionsAdderTest extends BaseUserTestCase
{
/**
* @var RoleRepository
*/
private $role;
/**
* @var UserRepository
*/
private $user;

public function setUp()
{
parent::setUp();
$this->role = app(RoleRepository::class);
$this->user = app(UserRepository::class);

$this->role->create([
'name' => 'Admin',
'slug' => 'admin',
'permissions' => [
'dashboard.index' => true,
]
]);
$this->user->create([
'email' => 'n.widart@gmail.com',
'password' => 'demo1234',
'permissions' => ['dashboard.index' => true,],
]);
$this->app->config->set('asgard.user.permissions', [
'user.users' => [
'index' => 'user::users.list user',
'create' => 'user::users.create user',
],
]);
}

/** @test */
public function it_can_add_permissions_to_the_admin_role()
{
$role = $this->role->findByName('Admin');

$this->assertCount(1, $role->permissions);

(new PermissionsAdder('User'))->addAll();

$role->refresh();
$this->assertCount(3, $role->permissions);
}
}

0 comments on commit cfa3997

Please sign in to comment.