1 | <?php |
||
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() { |
|
53 | |||
54 | /** |
||
55 | * @see Iterator::current |
||
56 | */ |
||
57 | 3 | public function current() { |
|
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() { |
|
106 | |||
107 | /** |
||
108 | * @see Iterator::rewind |
||
109 | */ |
||
110 | 3 | public function rewind() { |
|
114 | } |
||
115 |