JsonDumpReader::key()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
ccs 0
cts 4
cp 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 6
1
<?php
2
3
namespace Wikibase\EntityStore\Internal;
4
5
use Deserializers\Deserializer;
6
use Deserializers\Exceptions\DeserializationException;
7
use Iterator;
8
use Psr\Log\LoggerInterface;
9
use Wikibase\DataModel\Entity\EntityDocument;
10
11
/**
12
 * Internal class
13
14
 * @licence GPLv2+
15
 * @author Thomas Pellissier Tanon
16
 */
17
class JsonDumpReader implements Iterator {
18
19
	/**
20
	 * @var resource
21
	 */
22
	private $fileStream;
23
24
	/**
25
	 * @var Deserializer
26
	 */
27
	private $entityDeserializer;
28
29
	/**
30
	 * @var EntityDocument|null
31
	 */
32
	private $currentEntity = null;
33
34
	/**
35
	 * @var LoggerInterface
36
	 */
37
	private $logger;
38
39
	/**
40
	 * @param string $fileName
41
	 * @param Deserializer $entityDeserializer
42
	 * @param LoggerInterface $logger
43
	 */
44 3
	public function __construct( $fileName, Deserializer $entityDeserializer, LoggerInterface $logger ) {
45 3
		$this->fileStream = fopen( $fileName, 'r' );
46 3
		$this->entityDeserializer = $entityDeserializer;
47 3
		$this->logger = $logger;
48 3
	}
49
50 3
	public function __destruct() {
51 3
		fclose( $this->fileStream );
52 3
	}
53
54
	/**
55
	 * @see Iterator::current
56
	 */
57 3
	public function current() {
58 3
		return $this->currentEntity;
59
	}
60
61
	/**
62
	 * @see Iterator::next
63
	 */
64 3
	public function next() {
65 3
		$this->currentEntity = null;
66
67 3
		while( true ) {
68 3
			$line = fgets( $this->fileStream );
69
70 3
			if( $line === false ) {
71 3
				return;
72
			}
73
74 3
			$line = trim( $line, ", \n\t\r" );
75
76 3
			if( $line !== '' && $line[0] === '{' ) {
77 3
				$json = json_decode( $line, true );
78
				try {
79 3
					$this->currentEntity = $this->entityDeserializer->deserialize( $json );
80 3
					return;
81 1
				} catch( DeserializationException $e ) {
82 1
					$id = array_key_exists( 'id', $json ) ? $json['id'] : '';
83 1
					$this->logger->error( 'Deserialization of entity ' . $id . ' failed: ' . $e->getMessage() );
84
				}
85 1
			}
86 3
		}
87
	}
88
89
	/**
90
	 * @see Iterator::key
91
	 */
92
	public function key() {
93
		if ( $this->currentEntity === null ) {
94
			return null;
95
		}
96
97
		return $this->currentEntity->getId()->getSerialization();
98
	}
99
100
	/**
101
	 * @see Iterator::valid
102
	 */
103 3
	public function valid() {
104 3
		return $this->currentEntity !== null;
105
	}
106
107
	/**
108
	 * @see Iterator::rewind
109
	 */
110 3
	public function rewind() {
111 3
		fseek( $this->fileStream, 0 );
112 3
		$this->next();
113 3
	}
114
}
115