mirror of
https://github.com/flarum/framework.git
synced 2025-01-31 23:43:59 +08:00
Add some extra optional functionality to the Extend\Permission API
- Automatically serialise the attribute - Apply Permissible grant callbacks Need to consider splitting the $permission property into two arguments (currently have to explode by ‘.’)
This commit is contained in:
parent
7a487793a0
commit
f70f602f09
|
@ -2,18 +2,55 @@
|
|||
|
||||
use Illuminate\Foundation\Application;
|
||||
use Flarum\Core\Models\Permission as PermissionModel;
|
||||
use Flarum\Extend\SerializeAttributes;
|
||||
|
||||
class Permission implements ExtenderInterface
|
||||
{
|
||||
protected $permission;
|
||||
|
||||
protected $serialize = false;
|
||||
|
||||
protected $grant = [];
|
||||
|
||||
public function __construct($permission)
|
||||
{
|
||||
$this->permission = $permission;
|
||||
}
|
||||
|
||||
public function serialize($serialize = true)
|
||||
{
|
||||
$this->serialize = $serialize;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function grant($callback)
|
||||
{
|
||||
$this->grant[] = $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function extend(Application $app)
|
||||
{
|
||||
PermissionModel::addPermission($this->permission);
|
||||
|
||||
list($entity, $permission) = explode('.', $this->permission);
|
||||
|
||||
if ($this->serialize) {
|
||||
$extender = new SerializeAttributes(
|
||||
'Flarum\Api\Serializers\\'.ucfirst($entity).'Serializer',
|
||||
function (&$attributes, $model, $serializer) use ($permission) {
|
||||
$attributes['can'.ucfirst($permission)] = (bool) $model->can($serializer->actor->getUser(), $permission);
|
||||
}
|
||||
);
|
||||
|
||||
$extender->extend($app);
|
||||
}
|
||||
|
||||
foreach ($this->grant as $callback) {
|
||||
$model = 'Flarum\Core\Models\\'.ucfirst($entity);
|
||||
$model::grantPermission($permission, $callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,7 +19,7 @@ class SerializeAttributes implements ExtenderInterface
|
|||
{
|
||||
$app['events']->listen('Flarum\Api\Events\SerializeAttributes', function ($event) {
|
||||
if ($event->serializer instanceof $this->serializer) {
|
||||
call_user_func($this->callback, $event->attributes, $event->model, $event->serializer);
|
||||
call_user_func_array($this->callback, [&$event->attributes, $event->model, $event->serializer]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user