From 324fe21d735db7aaf2a61d3e38c3299756d8ab14 Mon Sep 17 00:00:00 2001 From: flashwave Date: Mon, 30 Sep 2024 17:38:08 +0000 Subject: [PATCH] Use attributes for JSON encoding. --- src/ClientInfo.php | 57 ++++++++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 20 deletions(-) diff --git a/src/ClientInfo.php b/src/ClientInfo.php index d0cbdd3..b63ab33 100644 --- a/src/ClientInfo.php +++ b/src/ClientInfo.php @@ -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;