Lines 89.47% 17 / 19
Functions and Methods 66.66% 2 / 3
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
DropPickedUpEvent 89.47% 17 / 19 66.66% 2 / 3 9.09 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 88.23% 15 / 17 0.00% 0 / 1 7.08
 summary 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Server\Event\Inventory;
6
7use Lorekeeper\Core\Item\ItemId;
8use Lorekeeper\Core\Support\Quantity;
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
19final readonly class DropPickedUpEvent implements Event
20{
21    use NamedAfterClass;
22
23    public function __construct(
24        public ItemId $item,
25        public Quantity $picked,
26        public Quantity $held,
27    ) {}
28
29    /** @return Option\Option<static> */
30    #[Override]
31    public static function from(Message $message): Option\Option
32    {
33        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'getDrop') {
34            return Option\none();
35        }
36
37        try {
38            $pickup = Type\shape([
39                'ItemID' => Type\positive_int(),
40                'bSuccess' => Type\int(),
41                'iQty' => Type\optional(Type\positive_int()),
42                'iQtyNow' => Type\optional(Type\positive_int()),
43            ], allowUnknownFields: true)->coerce($message->data);
44        } catch (CoercionException $exception) {
45            throw new MalformedEventException(static::class, 'picked up drop is invalid', $exception);
46        }
47
48        if ($pickup['bSuccess'] !== 1) {
49            return Option\none();
50        }
51
52        if (!array_key_exists('iQty', $pickup) || !array_key_exists('iQtyNow', $pickup)) {
53            throw new MalformedEventException(static::class, 'picked up drop has no quantities');
54        }
55
56        return Option\some(
57            new static(new ItemId($pickup['ItemID']), new Quantity($pickup['iQty']), new Quantity($pickup['iQtyNow'])),
58        );
59    }
60
61    #[Override]
62    public function summary(): string
63    {
64        return "Picked up {$this->picked->value} of item {$this->item->value}, holding {$this->held->value}";
65    }
66}