Skip to content

Commit

Permalink
Implement JsonSerializable (#115)
Browse files Browse the repository at this point in the history
Closes #110.


Co-authored-by: Gael DEBOST <zzgael@gmail.com>
  • Loading branch information
GrahamCampbell and zzgael committed Oct 17, 2021
1 parent 325dc6e commit 05249a8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "7.5-dev"
"dev-master": "7.6-dev"
},
"laravel": {
"providers": [
Expand Down
19 changes: 18 additions & 1 deletion src/BasePresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@

use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Support\Str;
use JsonSerializable;
use McCool\LaravelAutoPresenter\Exceptions\MethodNotFoundException;

abstract class BasePresenter implements UrlRoutable
abstract class BasePresenter implements UrlRoutable, JsonSerializable
{
/**
* The resource that is the object that was decorated.
Expand Down Expand Up @@ -106,6 +107,22 @@ public function resolveChildRouteBinding($childType, $value, $field)
return $this->wrappedObject->{Str::plural($childType)}()->where($field, $value)->first();
}

/**
* Retrieve the data which should be serialized to JSON.
*
* @return array
*/
public function jsonSerialize(): array
{
$attributes = [];

foreach ($this->wrappedObject->getAttributes() as $attribute => $value) {
$attributes[$attribute] = $this->$attribute;
}

return $attributes;
}

/**
* Magic method access initially tries for local fields, then defers to the
* decorated object.
Expand Down

0 comments on commit 05249a8

Please sign in to comment.