From 2c8b51689aac058b71f65b29cc81aec8950aab54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Bacik?= Date: Thu, 18 Apr 2024 17:19:08 +0200 Subject: [PATCH] Update Entity and mapper --- src/SDK/Client/Mapper/EntityMapper.php | 6 +++-- src/SDK/Entity.php | 32 ++++++++++++++++++++++---- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/SDK/Client/Mapper/EntityMapper.php b/src/SDK/Client/Mapper/EntityMapper.php index 974c39b..fc233c9 100644 --- a/src/SDK/Client/Mapper/EntityMapper.php +++ b/src/SDK/Client/Mapper/EntityMapper.php @@ -18,10 +18,12 @@ public function mapArray(array $data): object return new Entity( $data['id'] ?? null, $data['@id'] ?? null, - $data['slug'] ?? '', + $data['slug'] ?? null, $data['data'], $data['definition'] ?? null, - $data['parent'] ?? null, + !empty($data['parent']) + ? $data['parent']['@id'] ?? sprintf('/api/entities/%s', $data['parent']['id']) + : null, $data['private'] ?? false, $data['owned'] ?? false, ); diff --git a/src/SDK/Entity.php b/src/SDK/Entity.php index d82d055..1e0e029 100644 --- a/src/SDK/Entity.php +++ b/src/SDK/Entity.php @@ -6,15 +6,39 @@ readonly class Entity { + private const FIELD_TO_IRI = [ + 'parent' => '/api/entities/%s', + 'definition' => '/api/definitions/%s', + ]; + + public function __construct( public string|null $id, public string|null $iri, - public string $slug, - public array $data, + public string|null $slug, + public array|null $data, public string|null $definition, public string|null $parent = null, - public bool $private = false, - public bool $owned = false, + public bool|null $private = null, + public bool|null $owned = null, ) { } + + public function toArray(): array + { + return array_reduce( + array_keys(get_object_vars($this)), + function ($carry, $key) { + if ($this->{$key} !== null) { + if (array_key_exists($key, self::FIELD_TO_IRI)) { + $carry[$key] = sprintf(self::FIELD_TO_IRI[$key], $this->{$key}); + } else { + $carry[$key] = $this->{$key}; + } + } + return $carry; + }, + [] + ); + } }