Lines 94.73% 36 / 38
Methods 66.66% 2 / 3
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 93.54% 29 / 31 0.00% 0 / 1 10.03
 summary 100.00% 6 / 6 100.00% 1 / 1 1
21final readonly class PlayerVitalsUpdatedEvent extends PlayerUpdatedEvent
22{
23    public function __construct(
24        PlayerName $name,
25        public Vitals $vitals,
26    ) {
27        parent::__construct($name);
28    }
29
30    /** @return Option\Option<static> */
31    #[Override]
32    public static function from(Message $message): Option\Option
33    {
34        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'uotls') {
35            return Option\none();
36        }
37
38        try {
39            $update = Type\shape([
40                'unm' => Type\optional(Type\non_empty_string()),
41                'o' => Type\optional(Type\shape([
42                    'intHP' => Type\optional(Type\uint()),
43                    'intHPMax' => Type\optional(Type\uint()),
44                    'intMP' => Type\optional(Type\uint()),
45                    'intMPMax' => Type\optional(Type\uint()),
46                ], allowUnknownFields: true)),
47            ], allowUnknownFields: true)->coerce($message->data);
48        } catch (CoercionException $exception) {
49            throw new MalformedEventException(static::class, 'player name or vitals are invalid', $exception);
50        }
51
52        $name = $update['unm'] ?? null;
53        $health = $update['o']['intHP'] ?? null;
54        $maxHealth = $update['o']['intHPMax'] ?? null;
55        $mana = $update['o']['intMP'] ?? null;
56        $maxMana = $update['o']['intMPMax'] ?? null;
57        if ($name === null || $health === null || $maxHealth === null || $mana === null || $maxMana === null) {
58            return Option\none();
59        }
60
61        try {
62            return Option\some(
63                new static(
64                    new PlayerName($name),
65                    new Vitals(
66                        new Gauge(new Health($health), new Health($maxHealth)),
67                        new Gauge(new Mana($mana), new Mana($maxMana)),
68                    ),
69                ),
70            );
71        } catch (InvalidArgumentException $exception) {
72            throw new MalformedEventException(static::class, 'health or mana is above its maximum', $exception);
73        }
74    }
75
76    #[Override]
77    public function summary(): string
78    {
79        $health = $this->vitals->health;
80        $mana = $this->vitals->mana;
81
82        return (
83            "{$this->name->value} has {$health->current}/{$health->maximum} health"
84            . " and {$mana->current}/{$mana->maximum} mana"
85        );
86    }
87}