1
0
mirror of https://github.com/flarum/core.git synced 2025-10-12 23:44:27 +02:00

Rework public API based on events

This commit is contained in:
Toby Zerner
2015-07-18 22:59:47 +09:30
parent 5085c09c30
commit 57650fa648
136 changed files with 1157 additions and 1245 deletions

View File

@@ -1,10 +1,10 @@
<?php namespace Flarum\Api\Serializers;
use BadMethodCallException;
use Closure;
use Flarum\Core\Users\User;
use Flarum\Events\ApiAttributes;
use Flarum\Events\ApiRelationship;
use Tobscure\JsonApi\SerializerAbstract;
use Flarum\Api\Events\SerializeAttributes;
abstract class Serializer extends SerializerAbstract
{
@@ -13,13 +13,6 @@ abstract class Serializer extends SerializerAbstract
*/
public $actor;
/**
* An array of custom relation methods, grouped by subclass.
*
* @var array
*/
protected static $relationMethods = [];
/**
* @param User $actor
* @param array|null $include
@@ -39,7 +32,7 @@ abstract class Serializer extends SerializerAbstract
{
$attributes = $this->getDefaultAttributes($model);
event(new SerializeAttributes($this, $model, $attributes));
event(new ApiAttributes($this, $model, $attributes));
return $attributes;
}
@@ -57,13 +50,26 @@ abstract class Serializer extends SerializerAbstract
*/
protected function getRelationshipFromMethod($name)
{
if (isset(static::$relationMethods[$name])) {
return call_user_func(static::$relationMethods[$name], $this);
if ($relationship = $this->getCustomRelationship($name)) {
return $relationship;
}
return parent::getRelationshipFromMethod($name);
}
/**
* Get a custom relationship.
*
* @param string $name
* @return mixed
*/
protected function getCustomRelationship($name)
{
return app('events')->until(
new ApiRelationship($this, $name)
);
}
/**
* Get a closure that returns a Collection/Resource representing a relation.
*
@@ -154,16 +160,4 @@ abstract class Serializer extends SerializerAbstract
{
return $this->getRelationship($serializer, $relation, true);
}
/**
* Add a custom relation to the model.
*
* @param string $name The name of the relation.
* @param callable $callback The callback to execute. This should return a
* relation closure {@see Serializer::getRelationship()}
*/
public static function setRelationMethod($name, callable $callback)
{
static::$relationMethods[get_called_class()][$name] = $callback;
}
}