Use attributes for JSON encoding.

This commit is contained in:
flash 2024-09-30 17:38:08 +00:00
parent 153abde3a2
commit 324fe21d73

View file

@ -5,10 +5,12 @@ use stdClass;
use JsonSerializable;
use RuntimeException;
use Stringable;
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;
use DeviceDetector\{ClientHints,DeviceDetector};
use Index\Json\{JsonProperty,JsonSerializableTrait};
class ClientInfo implements Stringable, JsonSerializable {
use JsonSerializableTrait;
private const SERIALIZE_VERSION = 1;
public function __construct(
@ -19,6 +21,39 @@ class ClientInfo implements Stringable, JsonSerializable {
private string $modelName
) {}
#[JsonProperty('version')]
public function getVersion(): int {
return self::SERIALIZE_VERSION;
}
#[JsonProperty('bot')]
public function getBotInfo(): bool|array|null {
if($this->botInfo === true || is_array($this->botInfo))
return $this->botInfo;
return null;
}
#[JsonProperty('client')]
public function getClientInfo(): ?array {
return $this->clientInfo;
}
#[JsonProperty('os')]
public function getOsInfo(): ?array {
return $this->osInfo;
}
#[JsonProperty('vendor', omitIfValue: '')]
public function getVendorName(): string {
return $this->brandName;
}
#[JsonProperty('model', omitIfValue: '')]
public function getModelName(): string {
return $this->modelName;
}
public function __toString(): string {
if($this->botInfo === true || is_array($this->botInfo)) {
if($this->botInfo === true)
@ -64,24 +99,6 @@ class ClientInfo implements Stringable, JsonSerializable {
return json_encode($this);
}
public function jsonSerialize(): mixed {
$data = new stdClass;
$data->version = self::SERIALIZE_VERSION;
if($this->botInfo === true || is_array($this->botInfo))
$data->bot = $this->botInfo;
if($this->clientInfo !== null)
$data->client = $this->clientInfo;
if($this->osInfo !== null)
$data->os = $this->osInfo;
if($this->brandName !== '')
$data->vendor = $this->brandName;
if($this->modelName !== '')
$data->model = $this->modelName;
return $data;
}
public static function decode(string $encoded): self {
$data = json_decode($encoded, true);
$version = $data['version'] ?? 0;