1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace UCD\Infrastructure\Repository\CharacterRepository\FileRepository; |
4
|
|
|
|
5
|
|
|
use UCD\Exception\UnexpectedValueException; |
6
|
|
|
use UCD\Infrastructure\Repository\CharacterRepository\FileRepository\RangeFile\IntervalTree; |
7
|
|
|
|
8
|
|
|
class RangeFiles implements \IteratorAggregate, \Countable |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var RangeFile[]|\SplObjectStorage |
12
|
|
|
*/ |
13
|
|
|
private $map; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var IntervalTree |
17
|
|
|
*/ |
18
|
|
|
private $tree; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param RangeFile[] $files |
22
|
|
|
*/ |
23
|
|
|
public function __construct(array $files = []) |
24
|
|
|
{ |
25
|
|
|
$ranges = []; |
26
|
|
|
$map = new \SplObjectStorage(); |
27
|
|
|
|
28
|
|
|
foreach ($files as $file) { |
29
|
|
|
$map->attach($file->getRange(), $file); |
30
|
|
|
array_push($ranges, $file->getRange()); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$this->map = $map; |
34
|
|
|
$this->tree = new IntervalTree($ranges); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param RangeFile $file |
39
|
|
|
* @return RangeFile |
40
|
|
|
*/ |
41
|
|
|
public function add(RangeFile $file) |
42
|
|
|
{ |
43
|
|
|
$this->map->attach($file->getRange(), $file); |
44
|
|
|
$this->tree->add($file->getRange()); |
45
|
|
|
|
46
|
|
|
return $file; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param int $value |
51
|
|
|
* @return RangeFile|null |
52
|
|
|
* @throws UnexpectedValueException |
53
|
|
|
*/ |
54
|
|
|
public function getForValue($value) |
55
|
|
|
{ |
56
|
|
|
$ranges = $this->tree->search($value); |
57
|
|
|
$count = count($ranges); |
58
|
|
|
|
59
|
|
|
if ($count === 0) { |
60
|
|
|
return null; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if ($count > 1) { |
64
|
|
|
throw new UnexpectedValueException(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$range = array_shift($ranges); |
68
|
|
|
|
69
|
|
|
return $this->map[$range]; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* {@inheritDoc} |
74
|
|
|
*/ |
75
|
|
|
public function getIterator() |
76
|
|
|
{ |
77
|
|
|
return new \ArrayIterator($this->getAllFiles()); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return RangeFile[] |
82
|
|
|
*/ |
83
|
|
|
private function getAllFiles() |
84
|
|
|
{ |
85
|
|
|
$all = []; |
86
|
|
|
$this->map->rewind(); |
87
|
|
|
|
88
|
|
|
while ($this->map->valid() === true) { |
89
|
|
|
array_push($all, $this->map->getInfo()); |
90
|
|
|
$this->map->next(); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
return $all; |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* {@inheritDoc} |
98
|
|
|
*/ |
99
|
|
|
public function count() |
100
|
|
|
{ |
101
|
|
|
return count($this->map); |
102
|
|
|
} |
103
|
|
|
} |