Skip to content

Instantly share code, notes, and snippets.

@sebastiaanluca
Last active November 14, 2018 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastiaanluca/00928469f666ec2c73df2da6ac66a5f4 to your computer and use it in GitHub Desktop.
Save sebastiaanluca/00928469f666ec2c73df2da6ac66a5f4 to your computer and use it in GitHub Desktop.

Usage

$user->scopeTo('tenant-42')->can('do-something');
$user->scopeToModel($tenant)->can('do-something');

If you're using the proxy object directly, you might also be able to scope global calls on the Bouncer class like canAny, etc. You should be able to either pass the Bouncer class instance, tweak, or extend the object to your liking.

<?php
declare(strict_types=1);
use Silber\Bouncer\BouncerFacade as Bouncer;
use Silber\Bouncer\Database\Scope\Scope;
class ScopedPermissionObject
{
/**
* @var object
*/
private $object;
/**
* @param object $object
*/
public function __construct(object $object)
{
$this->object = $object;
}
/**
* @param string $scope
*
* @return $this
*/
public function scope(string $scope)
{
Bouncer::scope()
->onlyRelations()
->dontScopeRoleAbilities()
->to($scope);
return $this;
}
/**
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public function __call($method, $parameters)
{
$result = $this->object->{$method}(...$parameters);
$this->reset();
return $result;
}
/**
* @return void
*/
private function reset() : void
{
Bouncer::scope(new Scope);
}
}
<?php
declare(strict_types=1);
use Illuminate\Database\Eloquent\Model;
trait ScopesPermissions
{
/**
* Limit ability or role checking to a given scope.
*
* @param string $scope
*
* @return \User\Support\Permissions\ScopedPermissionObject|$this
*/
public function scopeTo(string $scope)
{
return (new ScopedPermissionObject($this))->scope($scope);
}
/**
* Limit ability or role checking to a given model.
*
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return \User\Support\Permissions\ScopedPermissionObject|$this
*/
public function scopeToModel(Model $model)
{
return $this->scopeTo(
$this->getScopeFromModel($model)
);
}
/**
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return string
*/
private function getScopeFromModel(Model $model) : string
{
return $model->getMorphClass() . ':' . $model->id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment