Lines 100.00% 18 / 18
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% 12 / 12 100.00% 1 / 1 6
 summary 100.00% 5 / 5 100.00% 1 / 1 1
21final readonly class ItemsTurnedInEvent extends InventoryUpdatedEvent
22{
23    /** @param non-empty-list<TurnedInItem> $items */
24    public function __construct(
25        public array $items,
26    ) {}
27
28    /** @return Option\Option<static> */
29    #[Override]
30    public static function from(Message $message): Option\Option
31    {
32        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'turnIn') {
33            return Option\none();
34        }
35
36        try {
37            $listed = Type\non_empty_string()->coerce($message->data['sItems'] ?? null);
38        } catch (CoercionException $exception) {
39            throw new MalformedEventException(static::class, 'turned in items are missing', $exception);
40        }
41
42        $items = [];
43        foreach (explode(',', $listed) as $entry) {
44            $parts = [];
45            if (preg_match('/^([1-9]\d*):([1-9]\d*)$/', $entry, $parts) !== 1) {
46                throw new MalformedEventException(static::class, "turned in item '{$entry}' is not id:quantity");
47            }
48
49            $items[] = new TurnedInItem(new ItemId((int) $parts[1]), new Quantity((int) $parts[2]));
50        }
51
52        return Option\some(new static($items));
53    }
54
55    #[Override]
56    public function summary(): string
57    {
58        return 'Turned in '
59        . implode(', ', array_map(
60            static fn(TurnedInItem $item): string => "{$item->quantity->value} of item {$item->item->value}",
61            $this->items,
62        ));
63    }
64}