Lines 100.00% 14 / 14
Functions and Methods 100.00% 1 / 1
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
CombatRoundEvent 100.00% 14 / 14 100.00% 1 / 1 4 100.00% 1 / 1
 read n/a 0 / 0 n/a 0 / 0 0
 from 100.00% 14 / 14 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Server\Event\Combat;
6
7use Lorekeeper\Server\Event\Event;
8use Lorekeeper\Server\Event\NamedAfterClass;
9use Lorekeeper\Server\Exception\MalformedEventException;
10use Lorekeeper\Server\Message\JsonMessage;
11use Lorekeeper\Server\Message\Message;
12use Override;
13use Psl\Option;
14use Psl\Type;
15use Psl\Type\Exception\CoercionException;
16
17/**
18 * A round of combat changed the health, mana or state of monsters and players in the room.
19 */
20abstract readonly class CombatRoundEvent implements Event
21{
22    use NamedAfterClass;
23
24    /**
25     * @param array<positive-int, array{intHP?: non-negative-int, intMP?: non-negative-int, intState?: int<0, 2>}> $monsters
26     * @param array<non-empty-string, array{intHP?: non-negative-int, intMP?: non-negative-int, intState?: int<0, 2>}> $players
27     *
28     * @return Option\Option<static>
29     */
30    abstract protected static function read(array $monsters, array $players): Option\Option;
31
32    /** @return Option\Option<static> */
33    #[Override]
34    final public static function from(Message $message): Option\Option
35    {
36        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'ct') {
37            return Option\none();
38        }
39
40        $status = Type\shape([
41            'intHP' => Type\optional(Type\uint()),
42            'intMP' => Type\optional(Type\uint()),
43            'intState' => Type\optional(Type\int_range(min: 0, max: 2)),
44        ], allowUnknownFields: true);
45
46        try {
47            $round = Type\shape([
48                'm' => Type\optional(Type\dict(Type\positive_int(), $status)),
49                'p' => Type\optional(Type\dict(Type\non_empty_string(), $status)),
50            ], allowUnknownFields: true)->coerce($message->data);
51        } catch (CoercionException $exception) {
52            throw new MalformedEventException(static::class, 'combat round is invalid', $exception);
53        }
54
55        return static::read($round['m'] ?? [], $round['p'] ?? []);
56    }
57}