Lines 100.00% 60 / 60
Functions and Methods 100.00% 6 / 6
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ShopLoadedEvent 100.00% 60 / 60 100.00% 6 / 6 18 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 100.00% 43 / 43 100.00% 1 / 1 9
 summary 100.00% 3 / 3 100.00% 1 / 1 3
 price 100.00% 2 / 2 100.00% 1 / 1 2
 costs 100.00% 7 / 7 100.00% 1 / 1 1
 item 100.00% 4 / 4 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Server\Event\Shop;
6
7use InvalidArgumentException;
8use Lorekeeper\Core\Item\Inventory;
9use Lorekeeper\Core\Item\Item;
10use Lorekeeper\Core\Item\ItemId;
11use Lorekeeper\Core\Item\ItemPrice;
12use Lorekeeper\Core\Item\ItemTag;
13use Lorekeeper\Core\Support\Quantity;
14use Lorekeeper\Core\World\Currency\AdventureCoins;
15use Lorekeeper\Core\World\Currency\Gold;
16use Lorekeeper\Core\World\Shop\CurrencyShop;
17use Lorekeeper\Core\World\Shop\MergeCost;
18use Lorekeeper\Core\World\Shop\MergeShop;
19use Lorekeeper\Core\World\Shop\Shop;
20use Lorekeeper\Core\World\Shop\ShopId;
21use Lorekeeper\Core\World\Shop\ShopName;
22use Lorekeeper\Core\World\Shop\ShopTag;
23use Lorekeeper\Server\Event\Event;
24use Lorekeeper\Server\Event\Item\Helper\ItemKinds;
25use Lorekeeper\Server\Event\NamedAfterClass;
26use Lorekeeper\Server\Exception\MalformedEventException;
27use Lorekeeper\Server\Message\JsonMessage;
28use Lorekeeper\Server\Message\Message;
29use Override;
30use Psl\Option;
31use Psl\Type;
32use Psl\Type\Exception\CoercionException;
33
34/**
35 * The server sent a shop and the items it sells.
36 *
37 * @psalm-type ShopEntry = array{ItemID: positive-int, sName: non-empty-string, sType: string, iCost?: non-negative-int, bCoins?: bool, bUpg?: bool, turnin?: list<array{ItemID: positive-int, iQty: positive-int, ...}>, ...}
38 *
39 * @mago-expect lint:cyclomatic-complexity
40 */
41final readonly class ShopLoadedEvent implements Event
42{
43    use NamedAfterClass;
44
45    public function __construct(
46        public Shop $shop,
47    ) {}
48
49    /** @return Option\Option<static> */
50    #[Override]
51    public static function from(Message $message): Option\Option
52    {
53        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'loadShop') {
54            return Option\none();
55        }
56
57        try {
58            $info = Type\shape([
59                'ShopID' => Type\positive_int(),
60                'sName' => Type\non_empty_string(),
61                'bUpgrd' => Type\optional(Type\bool()),
62                'bMerge' => Type\optional(Type\bool()),
63                'bHouse' => Type\optional(Type\bool()),
64                'items' => Type\vec(Type\shape([
65                    'ItemID' => Type\positive_int(),
66                    'sName' => Type\non_empty_string(),
67                    'sType' => Type\string(),
68                    'iCost' => Type\optional(Type\uint()),
69                    'bCoins' => Type\optional(Type\bool()),
70                    'bUpg' => Type\optional(Type\bool()),
71                    'turnin' => Type\optional(Type\vec(Type\shape([
72                        'ItemID' => Type\positive_int(),
73                        'iQty' => Type\positive_int(),
74                    ], allowUnknownFields: true))),
75                ], allowUnknownFields: true)),
76            ], allowUnknownFields: true)->coerce($message->data['shopinfo'] ?? null);
77        } catch (CoercionException $exception) {
78            throw new MalformedEventException(static::class, 'shopinfo is missing or invalid', $exception);
79        }
80
81        $id = new ShopId($info['ShopID']);
82        $name = new ShopName($info['sName']);
83
84        $items = [];
85        $prices = [];
86        $costs = [];
87        foreach ($info['items'] as $entry) {
88            $items[] = self::item($entry);
89            $prices[$entry['ItemID']] = self::price($entry);
90            $costs[$entry['ItemID']] = self::costs($entry);
91        }
92
93        try {
94            /** @var Inventory<Item> $inventory */
95            $inventory = new Inventory($items);
96            $shop = $info['bMerge'] ?? false
97                ? new MergeShop($id, $name, $inventory, $costs)
98                : new CurrencyShop($id, $name, $inventory, $prices);
99        } catch (InvalidArgumentException $exception) {
100            throw new MalformedEventException(static::class, $exception->getMessage(), $exception);
101        }
102
103        if ($info['bUpgrd'] ?? false) {
104            $shop->tags->add(ShopTag::MemberOnly);
105        }
106
107        if ($info['bHouse'] ?? false) {
108            $shop->tags->add(ShopTag::House);
109        }
110
111        return Option\some(new static($shop));
112    }
113
114    #[Override]
115    public function summary(): string
116    {
117        $shop = $this->shop;
118        $count = $shop instanceof CurrencyShop || $shop instanceof MergeShop ? count($shop->inventory) : 0;
119
120        return "{$shop->name->value}: {$count} items";
121    }
122
123    /** @param ShopEntry $entry */
124    private static function price(array $entry): ItemPrice
125    {
126        $cost = $entry['iCost'] ?? 0;
127
128        return new ItemPrice($entry['bCoins'] ?? false ? new AdventureCoins($cost) : new Gold($cost));
129    }
130
131    /**
132     * @param ShopEntry $entry
133     *
134     * @return list<MergeCost>
135     */
136    private static function costs(array $entry): array
137    {
138        return array_map(
139            static fn(array $material): MergeCost => new MergeCost(
140                new ItemId($material['ItemID']),
141                new Quantity($material['iQty']),
142            ),
143            $entry['turnin'] ?? [],
144        );
145    }
146
147    /**
148     * @param ShopEntry $entry
149     *
150     * @throws MalformedEventException
151     */
152    private static function item(array $entry): Item
153    {
154        $item = ItemKinds::read($entry, static::class);
155
156        if ($entry['bUpg'] ?? false) {
157            $item->tags->add(ItemTag::MemberOnly);
158        }
159
160        return $item;
161    }
162}