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:
Toby Zerner 2015-05-18 13:51:30 +09:30
parent 7a487793a0
commit f70f602f09
2 changed files with 38 additions and 1 deletions

View File

@ -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);
}
}
}

View File

@ -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]);
}
});
}