forked from byte-it/openapi-spec-generator
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathResourceContainer.php
96 lines (76 loc) · 2.52 KB
/
ResourceContainer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace LaravelJsonApi\OpenApiSpec;
use LaravelJsonApi\Contracts\Schema\Schema;
use LaravelJsonApi\Contracts\Server\Server;
use LaravelJsonApi\Contracts\Store\QueriesAll;
use LaravelJsonApi\Core\Resources\JsonApiResource;
class ResourceContainer
{
protected Server $server;
/** @var \Illuminate\Support\Collection[] */
protected array $resources = [];
public function __construct(Server $server)
{
$this->server = $server;
}
/**
* @param mixed $model Model class as FQN, model instance or an Schema instance
*/
public function resource($model): JsonApiResource
{
$fqn = $this->getFQN($model);
if (! isset($this->resources[$fqn])) {
$this->loadResources($fqn);
}
$resource = $this->resources[$fqn]->first();
if (! $resource) {
throw new \RuntimeException(sprintf('No resource found for model [%s], make sure your database is seeded!', $fqn));
}
return $resource;
}
/**
* @param mixed $model
* @return JsonApiResource[]
*/
public function resources($model): array
{
$fqn = $this->getFQN($model);
if (! isset($this->resource[$fqn])) {
$this->loadResources($fqn);
}
$resources = $this->resources[$fqn]->toArray();
if (empty($resources)) {
throw new \RuntimeException(sprintf('No resources found for model [%s], make sure your database is seeded!', $fqn));
}
return $resources;
}
protected function getFQN($model): string
{
$fqn = $model;
if ($model instanceof Schema) {
$fqn = $model::model();
} elseif (is_object($model)) {
$fqn = get_class($model);
}
return $fqn;
}
protected function loadResources(string $model)
{
$schema = $this->server->schemas()->schemaForModel($model);
$repository = $schema->repository();
if ($repository instanceof QueriesAll) {
$this->resources[$model] = collect($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);
})->take(3);
$this->resources[$model] = $resources;
}
}
}