1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wikibase\JsonDumpReader\Reader; |
4
|
|
|
|
5
|
|
|
use Wikibase\JsonDumpReader\DumpReader; |
6
|
|
|
use Wikibase\JsonDumpReader\DumpReadingException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Package private |
10
|
|
|
* |
11
|
|
|
* @licence GNU GPL v2+ |
12
|
|
|
* @author Jeroen De Dauw < [email protected] > |
13
|
|
|
*/ |
14
|
|
|
class Bz2DumpReader implements DumpReader { |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
private $dumpFile; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var resource|null |
23
|
|
|
*/ |
24
|
|
|
private $handle = null; |
25
|
|
|
|
26
|
|
|
private $lines = [ '' ]; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $dumpFilePath |
30
|
|
|
*/ |
31
|
4 |
|
public function __construct( $dumpFilePath ) { |
32
|
4 |
|
$this->dumpFile = $dumpFilePath; |
33
|
4 |
|
} |
34
|
|
|
|
35
|
4 |
|
public function __destruct() { |
36
|
4 |
|
$this->closeReader(); |
37
|
4 |
|
} |
38
|
|
|
|
39
|
4 |
|
private function closeReader() { |
40
|
4 |
|
if ( is_resource( $this->handle ) ) { |
41
|
3 |
|
bzclose( $this->handle ); |
42
|
3 |
|
$this->handle = null; |
43
|
|
|
} |
44
|
4 |
|
} |
45
|
|
|
|
46
|
1 |
|
public function rewind() { |
47
|
1 |
|
$this->closeReader(); |
48
|
1 |
|
$this->initReader(); |
49
|
1 |
|
$this->lines = [ '' ]; |
50
|
1 |
|
} |
51
|
|
|
|
52
|
4 |
|
private function initReader() { |
53
|
4 |
|
if ( $this->handle === null ) { |
54
|
4 |
|
$this->handle = @bzopen( $this->dumpFile, 'r' ); |
55
|
|
|
|
56
|
4 |
|
if ( $this->handle === false ) { |
57
|
1 |
|
throw new DumpReadingException( 'Could not open file: ' . $this->dumpFile ); |
58
|
|
|
} |
59
|
|
|
} |
60
|
3 |
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return string|null |
64
|
|
|
* @throws DumpReadingException |
65
|
|
|
*/ |
66
|
4 |
|
public function nextJsonLine() { |
67
|
4 |
|
$this->initReader(); |
68
|
|
|
|
69
|
|
|
do { |
70
|
3 |
|
$line = $this->nextLine(); |
71
|
|
|
|
72
|
3 |
|
if ( $line === null ) { |
73
|
2 |
|
return null; |
74
|
|
|
} |
75
|
|
|
} |
76
|
3 |
|
while ( $line === '' || $line{0} !== '{' ); |
77
|
|
|
|
78
|
2 |
|
return rtrim( $line, ",\n\r" ); |
79
|
|
|
} |
80
|
|
|
|
81
|
3 |
|
private function nextLine() { |
82
|
3 |
|
while ( !feof( $this->handle ) && count( $this->lines ) === 1 ) { |
83
|
3 |
|
$readString = bzread( $this->handle, 4096 ); |
84
|
|
|
|
85
|
3 |
|
if ( bzerrno( $this->handle ) !== 0 ) { |
86
|
|
|
throw new DumpReadingException( 'Decompression error: ' . bzerrstr( $this->handle ) ); |
87
|
|
|
} |
88
|
|
|
|
89
|
3 |
|
if ( $readString === false ) { |
90
|
|
|
break; |
91
|
|
|
} |
92
|
|
|
|
93
|
3 |
|
$this->lines[0] .= $readString; |
94
|
3 |
|
$this->lines = explode( "\n", $this->lines[0] ); |
95
|
|
|
} |
96
|
|
|
|
97
|
3 |
|
return array_shift( $this->lines ); |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
} |
101
|
|
|
|