1
0
mirror of https://github.com/flarum/core.git synced 2025-10-14 00:15:51 +02:00

Refactor some APIs

This commit is contained in:
Toby Zerner
2015-06-18 12:45:14 +09:30
parent f2888ee65f
commit 6db3bd9178
17 changed files with 365 additions and 237 deletions

87
src/Extend/Model.php Normal file
View File

@@ -0,0 +1,87 @@
<?php namespace Flarum\Extend;
use Illuminate\Contracts\Container\Container;
use Closure;
class Model implements ExtenderInterface
{
protected $model;
protected $scopeVisible = [];
protected $allow = [];
protected $relations = [];
public function __construct($model)
{
$this->model = $model;
}
public function scopeVisible(Closure $callback)
{
$this->scopeVisible[] = $callback;
return $this;
}
public function allow($action, Closure $callback)
{
$this->allow[] = compact('action', 'callback');
return $this;
}
public function hasOne($relation, $related, $foreignKey = null, $localKey = null)
{
$this->relations[$relation] = function ($model) use ($relation, $related, $foreignKey, $localKey) {
return $model->hasOne($related, $foreignKey, $localKey, $relation);
};
return $this;
}
public function belongsTo($relation, $related, $foreignKey = null, $otherKey = null)
{
$this->relations[$relation] = function ($model) use ($relation, $related, $foreignKey, $otherKey) {
return $model->belongsTo($related, $foreignKey, $otherKey, $relation);
};
return $this;
}
public function hasMany($relation, $related, $foreignKey = null, $localKey = null)
{
$this->relations[$relation] = function ($model) use ($relation, $related, $foreignKey, $localKey) {
return $model->hasMany($related, $foreignKey, $localKey, $relation);
};
return $this;
}
public function belongsToMany($relation, $related, $table = null, $foreignKey = null, $otherKey = null)
{
$this->relations[$relation] = function ($model) use ($relation, $related, $table, $foreignKey, $otherKey) {
return $model->belongsToMany($related, $table, $foreignKey, $otherKey, $relation);
};
return $this;
}
public function extend(Container $container)
{
$model = $this->model;
foreach ($this->relations as $relation => $callback) {
$model::addRelationship($relation, $callback);
}
foreach ($this->scopeVisible as $callback) {
$model::scopeVisible($callback);
}
foreach ($this->allow as $info) {
$model::allow($info['action'], $info['callback']);
}
}
}