|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Smr; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
|
|
7
|
|
|
class PlayerLevel { |
|
8
|
|
|
|
|
9
|
|
|
/** @var array<int, self> */ |
|
10
|
|
|
private static array $CACHE_LEVELS = []; |
|
11
|
|
|
|
|
12
|
|
|
public static function clearCache(): void { |
|
13
|
|
|
self::$CACHE_LEVELS = []; |
|
14
|
|
|
} |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @return array<int, self> |
|
18
|
|
|
*/ |
|
19
|
|
|
public static function getAll(): array { |
|
20
|
|
|
if (empty(self::$CACHE_LEVELS)) { |
|
21
|
|
|
$db = Database::getInstance(); |
|
22
|
|
|
$dbResult = $db->read('SELECT * FROM level'); |
|
23
|
|
|
foreach ($dbResult->records() as $dbRecord) { |
|
24
|
|
|
$levelID = $dbRecord->getInt('level_id'); |
|
25
|
|
|
self::$CACHE_LEVELS[$levelID] = new self( |
|
26
|
|
|
id: $levelID, |
|
27
|
|
|
name: $dbRecord->getString('level_name'), |
|
28
|
|
|
expRequired: $dbRecord->getInt('requirement'), |
|
29
|
|
|
); |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
|
|
return self::$CACHE_LEVELS; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public static function get(int $exp): self { |
|
36
|
|
|
foreach (array_reverse(self::getAll()) as $level) { |
|
37
|
|
|
if ($exp >= $level->expRequired) { |
|
38
|
|
|
return $level; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
throw new Exception('Failed to properly determine level from exp: ' . $exp); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public static function getMax(): int { |
|
45
|
|
|
$levels = self::getAll(); |
|
46
|
|
|
if (count($levels) == 0) { |
|
47
|
|
|
throw new Exception('Cannot get the max level, no levels were found'); |
|
48
|
|
|
} |
|
49
|
|
|
return max(array_keys($levels)); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function __construct( |
|
53
|
|
|
public readonly int $id, |
|
54
|
|
|
public readonly string $name, |
|
55
|
|
|
public readonly int $expRequired, |
|
56
|
|
|
) {} |
|
57
|
|
|
|
|
58
|
|
|
public function next(): self { |
|
59
|
|
|
// Return current level if on the last level |
|
60
|
|
|
return self::getAll()[$this->id + 1] ?? $this; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
} |
|
64
|
|
|
|