From 4cba2b877ac21fed8f377b3b6214295f8baed357 Mon Sep 17 00:00:00 2001 From: Radoslaw Mejer Date: Mon, 3 May 2021 23:19:06 +0200 Subject: [PATCH] Add JsonResource --- src/JsonResource.php | 49 +++++++++++++++++++ tests/Integration/JsonResourceTest.php | 66 ++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 src/JsonResource.php create mode 100644 tests/Integration/JsonResourceTest.php 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'] + ], + ]; + } +}