Passed
Push — master ( 0595aa...1ed9d2 )
by Sergio
01:27
created

JsonCollectionParser::openFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: sergio.rodenas
5
 * Date: 15/5/18
6
 * Time: 19:58
7
 */
8
9
namespace Rodenastyle\StreamParser\Services;
10
11
12
use JsonCollectionParser\Parser;
13
use Rodenastyle\StreamParser\Exceptions\IncompleteParseException;
14
use JsonCollectionParser\Listener;
15
use JsonStreamingParser\Parser as StreamingParser;
16
17
class JsonCollectionParser extends Parser
18
{
19
	/**
20
	 * @param string $filePath Source file path
21
	 * @param callback|callable $itemCallback Callback
22
	 * @param bool $assoc Parse as associative arrays
23
	 *
24
	 * @throws \Exception
25
	 */
26 4
	public function parse($filePath, $itemCallback, $assoc = true)
27
	{
28 4
		$this->checkCallback($itemCallback);
29
30 4
		$stream = $this->openFile($filePath);
31
32
		try {
33 4
			$listener = new Listener($itemCallback, $assoc);
34 4
			$this->parser = new StreamingParser(
35 4
				$stream,
36 4
				$listener,
37 4
				$this->getOption('line_ending'),
38 4
				$this->getOption('emit_whitespace')
39
			);
40 4
			$this->parser->parse();
41
		} catch (\Exception $e) {
42
			fclose($stream);
43
			throw $e;
44
		}
45
46 4
		if( ! fclose($stream)){
47
			throw new IncompleteParseException();
48
		}
49 4
	}
50
51
	/**
52
	 * @param string $filePath
53
	 *
54
	 * @return resource
55
	 * @throws \Exception
56
	 */
57 4
	protected function openFile($filePath)
58
	{
59 4
		$stream = @fopen($filePath, 'r');
60 4
		if (false === $stream) {
61
			throw new \Exception('Unable to open file for read: ' . $filePath);
62
		}
63
64 4
		return $stream;
65
	}
66
}
67