Lines 100.00% 35 / 35
Methods 100.00% 3 / 3
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 100.00% 30 / 30 100.00% 1 / 1 9
 summary 100.00% 4 / 4 100.00% 1 / 1 1
23final readonly class ItemsEnhancedEvent extends InventoryUpdatedEvent
24{
25    /** @param non-empty-list<ItemId> $items */
26    public function __construct(
27        public array $items,
28        public Enhancement $enhancement,
29        public Gold $paid,
30    ) {}
31
32    /** @return Option\Option<static> */
33    #[Override]
34    public static function from(Message $message): Option\Option
35    {
36        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'enhanceItemShop') {
37            return Option\none();
38        }
39
40        try {
41            $answer = Type\shape([
42                'bSuccess' => Type\int(),
43                'ItemIDs' => Type\optional(Type\non_empty_vec(Type\positive_int())),
44                'EnhPID' => Type\optional(Type\int()),
45                'EnhLvl' => Type\optional(Type\int_range(min: 1, max: 100)),
46                'EnhRty' => Type\optional(Type\int()),
47                'iCost' => Type\optional(Type\uint()),
48            ], allowUnknownFields: true)->coerce($message->data);
49        } catch (CoercionException $exception) {
50            throw new MalformedEventException(static::class, 'the enhanced items are invalid', $exception);
51        }
52
53        if ($answer['bSuccess'] !== 1) {
54            return Option\none();
55        }
56
57        $type = Enhancements::type($answer['EnhPID'] ?? 0);
58        $rarity = Enhancements::rarity($answer['EnhRty'] ?? 0, static::class);
59        $items = $answer['ItemIDs'] ?? null;
60        $level = $answer['EnhLvl'] ?? null;
61        if ($type === null || $rarity === null || $items === null || $level === null) {
62            throw new MalformedEventException(
63                static::class,
64                'a successful enhancement names no items, type, rarity or level',
65            );
66        }
67
68        return Option\some(
69            new static(
70                array_map(static fn(int $item): ItemId => new ItemId($item), $items),
71                new Enhancement($type, $rarity, new ItemLevel($level), Option\none()),
72                new Gold($answer['iCost'] ?? 0),
73            ),
74        );
75    }
76
77    #[Override]
78    public function summary(): string
79    {
80        return (
81            count($this->items)
82            . " item(s) enhanced with {$this->enhancement->type->name} level {$this->enhancement->level->value}"
83        );
84    }
85}