Completed
Pull Request — master (#6)
by Jeroen De
08:53 queued 05:58
created

Bz2DumpReader   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 94.87%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 1
dl 0
loc 87
ccs 37
cts 39
cp 0.9487
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __destruct() 0 3 1
A rewind() 0 5 1
A nextJsonLine() 0 14 4
A closeReader() 0 6 2
A initReader() 0 9 3
B nextLine() 0 18 5
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