JsonCollectionParser::openFile()   A
last analyzed

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 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
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, bool $assoc = true): void
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'),
0 ignored issues
show
Bug introduced by
It seems like $this->getOption('line_ending') can also be of type null; however, parameter $lineEnding of JsonStreamingParser\Parser::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

37
				/** @scrutinizer ignore-type */ $this->getOption('line_ending'),
Loading history...
38 4
				$this->getOption('emit_whitespace')
0 ignored issues
show
Bug introduced by
It seems like $this->getOption('emit_whitespace') can also be of type null; however, parameter $emitWhitespace of JsonStreamingParser\Parser::__construct() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

38
				/** @scrutinizer ignore-type */ $this->getOption('emit_whitespace')
Loading history...
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