-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdValueStore.php
More file actions
85 lines (62 loc) · 2.04 KB
/
Copy pathIdValueStore.php
File metadata and controls
85 lines (62 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace Echron\DataTypes;
use Echron\DataTypes\Exception\NotInCollectionException;
use Echron\DataTypes\Exception\ObjectAlreadyInCollectionException;
class IdValueStore
{
private array $hashMap = [];
private array $reversedHashMap = [];
public function __construct()
{
}
public function add(int $key, mixed $value, bool $overwriteIfExist = false): void
{
if (!$overwriteIfExist && \array_key_exists($key, $this->hashMap)) {
throw new ObjectAlreadyInCollectionException('There is already a value with key "' . $key . '"');
}
$this->reversedHashMap[$value] = $key;
$this->hashMap[$key] = $value;
}
public function getValueByKey(int $key): mixed
{
//TODO: isset or key_exists?
// if (!\key_exists($key, $this->hashMap)) {
if (!isset($this->hashMap[$key])) {
throw new NotInCollectionException('Key "' . $key . '" does not exist');
}
return $this->hashMap[$key];
}
public function getKeyByValue(mixed $value): int
{
//TODO: isset or key_exists?
// if (!\key_exists($value, $this->reversedHashMap)) {
if (!isset($this->reversedHashMap[$value])) {
throw new NotInCollectionException('Value "' . $value . '" does not exist (' . \implode(', ', $this->reversedHashMap) . ')');
}
return $this->reversedHashMap[$value];
}
public function removeByKey(int $key): void
{
$value = $this->getValueByKey($key);
unset($this->hashMap[$key]);
unset($this->reversedHashMap[$value]);
}
public function removeByValue(mixed $value): void
{
$key = $this->getKeyByValue($value);
unset($this->hashMap[$key]);
unset($this->reversedHashMap[$value]);
}
/**
* @return int[]
*/
public function getKeys(): array
{
return \array_values($this->reversedHashMap);
}
public function hasKey(int $key): bool
{
return isset($this->hashMap[$key]);
}
}