Lines 100.00% 21 / 21
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
BestEnhancement 100.00% 21 / 21 100.00% 3 / 3 9 100.00% 1 / 1
 for 100.00% 9 / 9 100.00% 1 / 1 3
 strength 100.00% 4 / 4 100.00% 1 / 1 1
 improves 100.00% 8 / 8 100.00% 1 / 1 5
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Bot\Abilities\Gear;
6
7use Lorekeeper\Core\Item\Equipment\Equipment;
8use Lorekeeper\Core\Item\Equipment\Traits\Enchantable;
9use Lorekeeper\Core\Item\Misc\Enhancement\Enhancement;
10use Lorekeeper\Core\Item\Misc\Enhancement\EnhancementItem;
11use Lorekeeper\Core\Item\Misc\Enhancement\EnhancementRarity;
12use Lorekeeper\Core\Item\Misc\Enhancement\EnhancementType;
13use Lorekeeper\Core\Player\Hero\Hero;
14use Lorekeeper\Core\World\Shop\CurrencyShop;
15
16final readonly class BestEnhancement
17{
18    public static function for(
19        Equipment&Enchantable $held,
20        EnhancementType $type,
21        CurrencyShop $shop,
22        Hero $hero,
23    ): ?EnhancementItem {
24        $usable = UsableEnhancements::among($shop, $held, $hero);
25        usort(
26            $usable,
27            static fn(EnhancementItem $a, EnhancementItem $b): int => (
28                self::strength($b->enhancement) <=> self::strength($a->enhancement)
29            ),
30        );
31        $best = $usable[0] ?? null;
32
33        return $best !== null && self::improves($best, $held, $type) ? $best : null;
34    }
35
36    private static function strength(Enhancement $enhancement): int
37    {
38        return (
39            ($enhancement->level->value * 100)
40            + (int) array_search($enhancement->rarity, EnhancementRarity::cases(), strict: true)
41        );
42    }
43
44    private static function improves(EnhancementItem $best, Enchantable $held, EnhancementType $type): bool
45    {
46        $current = $held->enhancement->unwrapOr(null);
47        if ($current?->type === EnhancementType::Unhandled || $best->enhancement->type === EnhancementType::Unhandled) {
48            return false;
49        }
50
51        return (
52            $current === null
53            || $current->type !== $type
54            || self::strength($current) < self::strength($best->enhancement)
55        );
56    }
57}