/** * Execute the console command. * * @return void */ public function handle() { $roles = $this->file->getRequire(base_path(config('trust.permissions'))); $this->call('trust:permissions'); $all = Permission::all(['id', 'slug']); $create = 0; $update = 0; foreach ($roles as $slug => $attributes) { $role = $this->findRole($slug); if ($role) { if ($this->option('force')) { ++$update; $role->update($attributes + compact('slug')); } } else { ++$create; $role = Role::create($attributes + compact('slug')); } $permissions = array_reduce(Arr::get($attributes, 'permissions', []), function (Collection $result, string $name) use($all) { if (hash_equals('*', $name)) { return $all->pluck('id'); } if ($all->count() === $result->count()) { return $result; } $filtered = $all->filter(function (Permission $permission) use($name) { return Str::is($name, $permission->slug); })->pluck('id'); return $result->merge($filtered); }, new Collection()); $role->permissions()->sync($permissions->toArray()); } $total = $create + $update; $this->line("Installed {$total} roles. <info>({$create} new roles, {$update} roles synced)</info>"); }
public function test_it_has_relations() { $role = Role::create(['name' => 'Foo', 'slug' => 'foo']); $this->assertTrue($role->users instanceof Collection); $this->assertTrue($role->users() instanceof BelongsToMany); $this->assertTrue($role->permissions instanceof Collection); $this->assertTrue($role->permissions() instanceof BelongsToMany); }
public function test_it_can_check_permission_through_role() { $user = $this->createUser(); $this->assertFalse($user->hasPermissionTo('create-post')); $permission = Permission::create(['name' => 'Create post', 'slug' => 'create-post']); $role = Role::create(['name' => 'Author', 'slug' => 'author']); $role->permissions()->attach($permission); $user->roles()->attach($role); $user->refreshPermissions(); $this->assertTrue($user->hasPermissionTo('create-post'), 'user cannot create post'); }