Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
17 / 17 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| JsonMessage | |
100.00% |
17 / 17 |
|
100.00% |
2 / 2 |
7 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| from | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
6 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AqwSocketClient\Messages; |
| 6 | |
| 7 | use AqwSocketClient\Enums\JsonMessageType; |
| 8 | use AqwSocketClient\Interfaces\MessageInterface; |
| 9 | use Override; |
| 10 | |
| 11 | /** |
| 12 | * Represents a parsed socket message that is structured as a **single JSON object**. |
| 13 | * |
| 14 | * This class is responsible for decoding the raw string data received from the |
| 15 | * server and extracting the core message details: its type and raw associated data. |
| 16 | */ |
| 17 | final class JsonMessage implements MessageInterface |
| 18 | { |
| 19 | /** |
| 20 | * Constructs the JsonMessage object with the parsed message type and data. |
| 21 | * |
| 22 | * @param JsonMessageType $type The enumerated type identifying the action requested/reported. |
| 23 | * @param array $data The raw array structure associated with this message's content. |
| 24 | */ |
| 25 | private function __construct( |
| 26 | public readonly JsonMessageType $type, |
| 27 | public readonly array $data, |
| 28 | public readonly string $raw, |
| 29 | ) {} |
| 30 | |
| 31 | /** |
| 32 | * Attempts to create a JsonMessage object by decoding the raw JSON string received from the socket. |
| 33 | * |
| 34 | * This factory method handles the necessary checks and extraction logic to transform |
| 35 | * the raw message into a structured object. |
| 36 | * |
| 37 | * @param string $message The raw string data received from the socket (expected to be a single JSON object). |
| 38 | * @return JsonMessage|false The successfully created message object, or **false** if parsing fails |
| 39 | * due to invalid JSON, missing required fields, or an unknown message type. |
| 40 | * @mago-ignore analyzer:mixed-assignment |
| 41 | */ |
| 42 | #[Override] |
| 43 | public static function from(string $message): JsonMessage|false |
| 44 | { |
| 45 | $json = json_decode($message, true); |
| 46 | |
| 47 | if (!is_array($json)) { |
| 48 | return false; |
| 49 | } |
| 50 | |
| 51 | $b = $json['b'] ?? null; |
| 52 | if (!is_array($b)) { |
| 53 | return false; |
| 54 | } |
| 55 | |
| 56 | $messageData = $b['o'] ?? null; |
| 57 | if (!is_array($messageData)) { |
| 58 | return false; |
| 59 | } |
| 60 | |
| 61 | $cmd = $messageData['cmd'] ?? null; |
| 62 | if (!is_string($cmd)) { |
| 63 | return false; |
| 64 | } |
| 65 | |
| 66 | $type = JsonMessageType::tryFrom($cmd); |
| 67 | if ($type === null) { |
| 68 | return false; |
| 69 | } |
| 70 | |
| 71 | return new self($type, $messageData, $message); |
| 72 | } |
| 73 | } |