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