Skip to content

Commit

Permalink
Feature/transform eloquent models (#47)
Browse files Browse the repository at this point in the history
* Forward port feature from v2 to allow more broad transformation of eloquent models

* Apply fixes from StyleCI (#46)
  • Loading branch information
specialtactics authored Jun 5, 2021
1 parent 8777d23 commit 9d875e7
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/Transformers/RestfulTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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');
}
Expand All @@ -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;

Expand Down Expand Up @@ -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
*
Expand Down

0 comments on commit 9d875e7

Please sign in to comment.