Add the preferences API for apps and users

This commit is contained in:
envoyr committed 2026-11-06 19:28:23 +00:00
1 parent 90dac3a5a6
commit 802f52ce93
10 files changed
+703

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Anikeen\Id\Resources;
/**
* A preference of a user: a JSON value under a namespace and a key. `version` is opaque: it only
* goes up (per user, not consecutive per key) and is what ifVersion (`If-Match`) compares.
* JSON objects come back as stdClass, so `{}` stays an object.
*
* @property string $namespace
* @property string $key
* @property mixed $value
* @property int $version
* @property string $updated_at
* @property object{type: string, client_id: ?string} $updated_by `type` "user" (written with a user token) or "app"
*/
class Preference extends BaseResource
{
/**
* The write that returned this preference created the key (201). False for reads, updates and
* writes of the value already stored.
*/
public function wasCreated(): bool
{
return $this->result->response()?->getStatusCode() === 201;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace Anikeen\Id\Resources;
/**
* The preferences of a user in one namespace, sorted by key (at most 50, no pagination).
*/
class Preferences extends BaseCollection
{
/**
* The preference of a key; null when it isn't set. Reads the list, no request.
*/
public function find(string $id): ?Preference
{
$data = $this->item($id);
if ($data === null) {
return null;
}
$result = clone $this->result;
$result->data = $data;
return new Preference(fn () => $result);
}
/**
* The value of a key, or $default when it isn't set.
*/
public function get(string $key, mixed $default = null): mixed
{
$data = $this->item($key);
return $data !== null ? $data->value : $default;
}
public function has(string $key): bool
{
return $this->item($key) !== null;
}
/**
* The values by key.
*
* @return array<string, mixed>
*/
public function values(): array
{
$values = [];
foreach ((array) $this->result->data as $data) {
$values[$data->key] = $data->value;
}
return $values;
}
private function item(string $key): ?object
{
foreach ((array) $this->result->data as $data) {
if (($data->key ?? null) === $key) {
return $data;
}
}
return null;
}
}