Lines 100.00% 10 / 10
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
JsonMessage 100.00% 10 / 10 100.00% 2 / 2 3 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 100.00% 9 / 9 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Server\Message;
6
7use Override;
8use Psl\Option;
9use Psl\Type;
10use Psl\Type\Exception\CoercionException;
11
12final readonly class JsonMessage implements Message
13{
14    /** @param array<string, mixed> $data */
15    public function __construct(
16        public array $data,
17        public string $raw,
18    ) {}
19
20    /** @return Option\Option<static> */
21    #[Override]
22    public static function from(string $message): Option\Option
23    {
24        $type = Type\json_decoded(Type\shape([
25            'b' => Type\shape([
26                'o' => Type\dict(Type\string(), Type\mixed()),
27            ], allowUnknownFields: true),
28        ], allowUnknownFields: true));
29
30        try {
31            $json = $type->coerce($message);
32        } catch (CoercionException) {
33            return Option\none();
34        }
35
36        return Option\some(new self($json['b']['o'], $message));
37    }
38}