From 57ffa867c895eef478d3f923bca81b3f8659bca2 Mon Sep 17 00:00:00 2001 From: Toby Zerner Date: Tue, 15 Oct 2019 18:56:51 +1030 Subject: [PATCH] Update resource definition API to allow extending schema --- src/JsonApi.php | 8 ++++++-- src/ResourceType.php | 25 +++++++++++++++++-------- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/JsonApi.php b/src/JsonApi.php index b5d716c..d9debae 100644 --- a/src/JsonApi.php +++ b/src/JsonApi.php @@ -31,9 +31,13 @@ final class JsonApi implements RequestHandlerInterface $this->baseUrl = $baseUrl; } - public function resource(string $type, $adapter, Closure $buildSchema = null): void + public function resource(string $type): ResourceType { - $this->resources[$type] = new ResourceType($type, $adapter, $buildSchema); + if (! isset($this->resources[$type])) { + $this->resources[$type] = new ResourceType($type); + } + + return $this->resources[$type]; } public function getResources(): array diff --git a/src/ResourceType.php b/src/ResourceType.php index 09f403d..8ef2976 100644 --- a/src/ResourceType.php +++ b/src/ResourceType.php @@ -2,7 +2,6 @@ namespace Tobyz\JsonApiServer; -use Closure; use Tobyz\JsonApiServer\Adapter\AdapterInterface; use Tobyz\JsonApiServer\Schema\Type; @@ -10,14 +9,12 @@ final class ResourceType { private $type; private $adapter; - private $buildSchema; + private $schemaCallbacks = []; private $schema; - public function __construct(string $type, AdapterInterface $adapter, Closure $buildSchema = null) + public function __construct(string $type) { $this->type = $type; - $this->adapter = $adapter; - $this->buildSchema = $buildSchema; } public function getType(): string @@ -25,19 +22,31 @@ final class ResourceType return $this->type; } + public function adapter(AdapterInterface $adapter) + { + $this->adapter = $adapter; + + return $this; + } + public function getAdapter(): AdapterInterface { return $this->adapter; } + public function schema(callable $callback) + { + $this->schemaCallbacks[] = $callback; + + return $this; + } + public function getSchema(): Type { if (! $this->schema) { $this->schema = new Type; - if ($this->buildSchema) { - ($this->buildSchema)($this->schema); - } + run_callbacks($this->schemaCallbacks, [$this->schema]); } return $this->schema;