1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Smoren\PartialIntersection\Util; |
6
|
|
|
|
7
|
|
|
class UsageMap |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var array<string, array<string, int>> |
11
|
|
|
*/ |
12
|
|
|
protected array $addedMap = []; |
13
|
|
|
/** |
14
|
|
|
* @var array<string, int> |
15
|
|
|
*/ |
16
|
|
|
protected array $deletedMap = []; |
17
|
|
|
/** |
18
|
|
|
* @var bool |
19
|
|
|
*/ |
20
|
|
|
protected bool $strict; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param bool $strict |
24
|
|
|
*/ |
25
|
374 |
|
public function __construct(bool $strict) |
26
|
|
|
{ |
27
|
374 |
|
$this->strict = $strict; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Registers usage of the value by owner. |
32
|
|
|
* |
33
|
|
|
* @param mixed $value |
34
|
|
|
* @param string $owner |
35
|
|
|
* |
36
|
|
|
* @return void |
37
|
|
|
*/ |
38
|
318 |
|
public function addUsage($value, string $owner): void |
39
|
|
|
{ |
40
|
318 |
|
$hash = UniqueExtractor::getString($value, $this->strict); |
41
|
|
|
|
42
|
318 |
|
if (!isset($this->addedMap[$hash])) { |
43
|
318 |
|
$this->addedMap[$hash] = []; |
44
|
|
|
} |
45
|
|
|
|
46
|
318 |
|
if (!isset($this->addedMap[$hash][$owner])) { |
47
|
318 |
|
$this->addedMap[$hash][$owner] = 0; |
48
|
|
|
} |
49
|
|
|
|
50
|
318 |
|
$this->addedMap[$hash][$owner]++; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Unregister usage of the value. |
55
|
|
|
* |
56
|
|
|
* @param mixed $value |
57
|
|
|
* |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
208 |
|
public function deleteUsage($value): void |
61
|
|
|
{ |
62
|
208 |
|
$hash = UniqueExtractor::getString($value, $this->strict); |
63
|
|
|
|
64
|
208 |
|
if (!isset($this->deletedMap[$hash])) { |
65
|
208 |
|
$this->deletedMap[$hash] = 0; |
66
|
|
|
} |
67
|
|
|
|
68
|
208 |
|
$this->deletedMap[$hash]++; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Returns number of value's owners. |
73
|
|
|
* |
74
|
|
|
* @param mixed $value |
75
|
|
|
* |
76
|
|
|
* @return int |
77
|
|
|
*/ |
78
|
318 |
|
public function getOwnersCount($value): int |
79
|
|
|
{ |
80
|
318 |
|
$hash = UniqueExtractor::getString($value, $this->strict); |
81
|
318 |
|
$deletesCount = $this->deletedMap[$hash] ?? 0; |
82
|
|
|
|
83
|
318 |
|
return count(array_filter($this->addedMap[$hash] ?? [], fn ($count) => $count > $deletesCount)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|