From 7a65327ac49b2d8b6ff02e81c271c027e59af54e Mon Sep 17 00:00:00 2001 From: marinusvanvelzen Date: Tue, 19 Sep 2023 12:25:08 +0200 Subject: [PATCH] feat: use the repository for example generation if available --- sites.json | 10 ++++++++++ src/ResourceContainer.php | 14 +++++++++++++- tests/Support/Entities/Site.php | 11 ----------- 3 files changed, 23 insertions(+), 12 deletions(-) create mode 100644 sites.json diff --git a/sites.json b/sites.json new file mode 100644 index 0000000..97456e6 --- /dev/null +++ b/sites.json @@ -0,0 +1,10 @@ +{ + "example": { + "domain": "johnsmith.com", + "name": "Johns site" + }, + "foo": { + "domain": "foo.bar", + "name": "Foo Bar" + } +} diff --git a/src/ResourceContainer.php b/src/ResourceContainer.php index 12cbc7f..a366a6d 100644 --- a/src/ResourceContainer.php +++ b/src/ResourceContainer.php @@ -4,6 +4,7 @@ use LaravelJsonApi\Contracts\Schema\Schema; use LaravelJsonApi\Contracts\Server\Server; +use LaravelJsonApi\Contracts\Store\QueriesAll; use LaravelJsonApi\Core\Resources\JsonApiResource; class ResourceContainer @@ -33,7 +34,7 @@ public function resource($model): JsonApiResource $resource = $this->resources[$fqn]->first(); if (!$resource) { - throw new \RuntimeException(sprintf('No resource found for model [%s], make sure your database is seeded!', $fqn)); + throw new \RuntimeException(sprintfz('No resource found for model [%s], make sure your database is seeded!', $fqn)); } return $resource; @@ -77,6 +78,17 @@ protected function getFQN($model): string */ protected function loadResources(string $model) { + $schema = $this->server->schemas()->schemaForModel($model); + $repository = $schema->repository(); + + if ($repository instanceof QueriesAll) { + $this->resources[$model] = $repository->queryAll()->get()->map(function ($model) { + return $this->server->resources()->create($model); + })->take(3); + + return; + } + if (method_exists($model, 'all')) { $resources = $model::all()->map(function ($model) { return $this->server->resources()->create($model); diff --git a/tests/Support/Entities/Site.php b/tests/Support/Entities/Site.php index c6df3ff..f462528 100644 --- a/tests/Support/Entities/Site.php +++ b/tests/Support/Entities/Site.php @@ -5,7 +5,6 @@ namespace LaravelJsonApi\OpenApiSpec\Tests\Support\Entities; use Illuminate\Contracts\Support\Arrayable; -use Illuminate\Support\Collection; class Site implements Arrayable { @@ -51,16 +50,6 @@ public function getName(): ?string return $this->name; } - public static function all(): Collection - { - return collect([ - self::fromArray('example', [ - 'domain' => 'example.com', - 'name' => 'Johns Site', - ]), - ]); - } - public function setName(?string $name): Site { $this->name = $name;