Lines 100.00% 11 / 11
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ItemWornEvent 100.00% 11 / 11 100.00% 3 / 3 6 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 100.00% 9 / 9 100.00% 1 / 1 4
 summary 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Server\Event\Item;
6
7use Lorekeeper\Core\Item\ItemId;
8use Lorekeeper\Core\Player\PlayerSpawnId;
9use Lorekeeper\Server\Event\Event;
10use Lorekeeper\Server\Event\NamedAfterClass;
11use Lorekeeper\Server\Exception\MalformedEventException;
12use Lorekeeper\Server\Message\JsonMessage;
13use Lorekeeper\Server\Message\Message;
14use Override;
15use Psl\Option;
16use Psl\Type;
17use Psl\Type\Exception\CoercionException;
18
19/**
20 * A player in the room put on an item as a cosmetic.
21 */
22final readonly class ItemWornEvent implements Event
23{
24    use NamedAfterClass;
25
26    public function __construct(
27        public PlayerSpawnId $player,
28        public ItemId $itemId,
29    ) {}
30
31    /** @return Option\Option<static> */
32    #[Override]
33    public static function from(Message $message): Option\Option
34    {
35        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'wearItem') {
36            return Option\none();
37        }
38
39        try {
40            $data = Type\shape([
41                'uid' => Type\positive_int(),
42                'ItemID' => Type\positive_int(),
43            ], allowUnknownFields: true)->coerce($message->data);
44        } catch (CoercionException $exception) {
45            throw new MalformedEventException(static::class, 'worn item is missing or invalid', $exception);
46        }
47
48        return Option\some(new static(new PlayerSpawnId($data['uid']), new ItemId($data['ItemID'])));
49    }
50
51    #[Override]
52    public function summary(): string
53    {
54        return "Spawn {$this->player->value} wore item {$this->itemId->value}";
55    }
56}