Bz2DumpReader::nextJsonLine()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

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