1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Remorhaz\UCD\Tool; |
6
|
|
|
|
7
|
|
|
use Iterator; |
8
|
|
|
use IteratorAggregate; |
9
|
|
|
use Remorhaz\IntRangeSets\Range; |
10
|
|
|
use SplFileObject; |
11
|
|
|
use Throwable; |
12
|
|
|
|
13
|
|
|
final class PropertiesRangeIterator implements IteratorAggregate |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var SplFileObject |
18
|
|
|
*/ |
19
|
|
|
private $file; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var callable |
23
|
|
|
*/ |
24
|
|
|
private $onProgress; |
25
|
|
|
|
26
|
|
|
public function __construct(SplFileObject $file, callable $onProgress) |
27
|
|
|
{ |
28
|
|
|
$this->file = $file; |
29
|
|
|
$this->onProgress = $onProgress; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function getIterator(): Iterator |
33
|
|
|
{ |
34
|
|
|
while (!$this->file->eof()) { |
35
|
|
|
$line = $this->fetchNextLine($this->file); |
36
|
|
|
if (!isset($line)) { |
37
|
|
|
continue; |
38
|
|
|
} |
39
|
|
|
yield from $this->fetchPropertyRange($line); |
40
|
|
|
|
41
|
|
|
($this->onProgress)(strlen($line)); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function fetchNextLine(SplFileObject $file): ?string |
46
|
|
|
{ |
47
|
|
|
$line = $file->fgets(); |
48
|
|
|
if (false === $line) { |
49
|
|
|
throw new Exception\LineNotReadException($file->getFilename()); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return '' == $line ? null : $line; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function fetchPropertyRange(string $line): Iterator |
56
|
|
|
{ |
57
|
|
|
$dataWithComment = explode('#', $line, 2); |
58
|
|
|
$data = trim($dataWithComment[0] ?? ''); |
59
|
|
|
if ('' == $data) { |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
$rangeWithProp = explode(';', $data); |
63
|
|
|
$unSplitRange = trim($rangeWithProp[0] ?? null); |
|
|
|
|
64
|
|
|
$prop = trim($rangeWithProp[1] ?? null); |
65
|
|
|
if (!isset($unSplitRange, $prop)) { |
66
|
|
|
throw new Exception\InvalidLineException($line); |
67
|
|
|
} |
68
|
|
|
$splitRange = explode('..', $unSplitRange); |
69
|
|
|
$start = hexdec($splitRange[0]); |
70
|
|
|
$finish = isset($splitRange[1]) |
71
|
|
|
? hexdec($splitRange[1]) |
72
|
|
|
: $start; |
73
|
|
|
|
74
|
|
|
try { |
75
|
|
|
yield $prop => new Range($start, $finish); |
|
|
|
|
76
|
|
|
} catch (Throwable $e) { |
77
|
|
|
throw new Exception\RangeNotCreatedException($e); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|