diff --git a/src/JsonResource.php b/src/JsonResource.php new file mode 100644 index 0000000..8850f35 --- /dev/null +++ b/src/JsonResource.php @@ -0,0 +1,49 @@ +resource)) { + return []; + } + + if (is_array($this->resource)) { + return $this->resource; + } + + if ($this->resource instanceof Model) { + return array_merge( + $this->resource->attributesToArray(), + $this->wrapRelations($request) + ); + } + + return $this->resource->toArray(); + } + + private function wrapRelations($request): array + { + $getRelations = (function () { + return $this->getArrayableRelations(); + })->bindTo($this->resource, $this->resource); + + $relations = []; + + foreach ($getRelations() as $key => $value) { + if ($this->resource::$snakeAttributes) { + $key = Str::snake($key); + } + + $relations[$key] = resource($value)->toArray($request); + } + + return $relations; + } +} diff --git a/tests/Integration/JsonResourceTest.php b/tests/Integration/JsonResourceTest.php new file mode 100644 index 0000000..7099de0 --- /dev/null +++ b/tests/Integration/JsonResourceTest.php @@ -0,0 +1,66 @@ + 'Lorem ipsum']); + $post->setRelation('dummy_tags', collect([ + new Tag(['name' => 'foo']), + new Tag(['name' => 'bar']), + ])); + + $resource = new JsonResource($post); + $expected = [ + 'text' => 'Lorem ipsum', + 'dummy_tags' => [ + ['name' => 'foo', 'tag' => true], + ['name' => 'bar', 'tag' => true], + ], + ]; + + $this->assertEquals($expected, $resource->resolve()); + } + + /** + * @dataProvider otherResourcesProvider + */ + public function test_it_handles_other_resources($resource, $expected) + { + $this->assertEquals($expected, (new JsonResource($resource))->resolve()); + } + + public function otherResourcesProvider() + { + return [ + [null, []], + [['foo' => 'baz'], ['foo' => 'baz']], + [ + new class () implements Arrayable + { + public function toArray() + { + return ['foo' => 'baz']; + } + }, + ['foo' => 'baz'] + ], + ]; + } +}