From 9d875e7314b2118e3942c2d204101720f329db2f Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 5 Jun 2021 23:33:30 +1000 Subject: [PATCH] Feature/transform eloquent models (#47) * Forward port feature from v2 to allow more broad transformation of eloquent models * Apply fixes from StyleCI (#46) --- src/Transformers/RestfulTransformer.php | 31 ++++++++++++++++++++----- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/Transformers/RestfulTransformer.php b/src/Transformers/RestfulTransformer.php index 871c84d..4d2148b 100644 --- a/src/Transformers/RestfulTransformer.php +++ b/src/Transformers/RestfulTransformer.php @@ -5,6 +5,7 @@ use League\Fractal\TransformerAbstract; use Specialtactics\L5Api\APIBoilerplate; use Specialtactics\L5Api\Models\RestfulModel; +use Illuminate\Database\Eloquent\Model as EloquentModel; class RestfulTransformer extends TransformerAbstract { @@ -22,10 +23,16 @@ class RestfulTransformer extends TransformerAbstract */ public function transform($object) { - if (is_object($object) && $object instanceof RestfulModel) { - $transformed = $this->transformRestfulModel($object); - } elseif (is_object($object) && $object instanceof \stdClass) { - $transformed = $this->transformStdClass($object); + if (is_object($object)) { + if ($object instanceof RestfulModel) { + $transformed = $this->transformRestfulModel($object); + } elseif ($object instanceof EloquentModel) { + $transformed = $this->transformEloquentModel($object); + } elseif ($object instanceof \stdClass) { + $transformed = $this->transformStdClass($object); + } else { + throw new \Exception('Unexpected object type encountered in transformer'); + } } else { throw new \Exception('Unexpected object type encountered in transformer'); } @@ -52,12 +59,12 @@ public function transformStdClass($object) } /** - * Transform an eloquent object into a jsonable array + * Transform a restful model object into a jsonable array * * @param RestfulModel $model * @return array */ - public function transformRestfulModel(RestfulModel $model) + public function transformRestfulModel(EloquentModel $model) { $this->model = $model; @@ -105,6 +112,18 @@ public function transformRestfulModel(RestfulModel $model) return $transformed; } + /** + * At the moment, there is no difference in implementation between this and the more specific Restfulmodel, + * however in the future there may be + * + * @param EloquentModel $model + * @return array + */ + public function transformEloquentModel(EloquentModel $model) + { + return $this->transformRestfulModel($model); + } + /** * Transform the keys of the object to the correct case as required *