nasrulhazim
7/31/2018 - 2:30 AM

WIP: Spatie Laravel Permission - Extend Give and Revoke Permission to Work with Given Guard Name

WIP: Spatie Laravel Permission - Extend Give and Revoke Permission to Work with Given Guard Name

<?php 

namespace App\Traits;

use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;

trait HasRolePermissionTrait {
	use HasRoles;

	/**
     * Revoke the given permission.
     *
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
     * @param string
     *
     * @return $this
     */
    public function revokePermissionToWithGuard($permission, $guard_name)
    {
    	// if permission exist for the given guard, revoke
        if (! $this->hasPermissionTo($permission, $guard_name)) {
        	throw GuardDoesNotMatch::create($guard_name, $this->getGuardNames());
        }

        $this->permissions()->detach($this->getStoredPermission($permission));

        $this->forgetCachedPermissions();

        return $this;
    }

    /**
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
     *
     * @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
     */
    protected function getStoredPermissionByGuardName($permissions, $guard_name)
    {
        if (is_numeric($permissions)) {
            return app(Permission::class)->findById($permissions, $guard_name);
        }

        if (is_string($permissions)) {
            return app(Permission::class)->findByName($permissions, $guard_name);
        }

        if (is_array($permissions)) {
            return app(Permission::class)
                ->whereIn('name', $permissions)
                ->whereIn('guard_name', $this->getGuardNames())
                ->get();
        }

        return $permissions;
    }

    /**
     * Grant the given permission(s) to a role.
     *
     * @param array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
     * @param string
     * 
     * @return $this
     */
    public function givePermissionToWithGuard($permissions, $guard_name)
    {
        $permissions = collect($permissions)
            ->flatten()
            ->map(function ($permission) {
                return $this->getStoredPermission($permission);
            })
            ->each(function ($permission) {
                $this->ensureModelSharesGuard($permission);
            })
            ->all();

        $this->permissions()->saveMany($permissions);

        $this->forgetCachedPermissions();

        return $this;
    }
}