JsonParser   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 60
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A parse() 0 22 3
A decodeJson() 0 9 1
1
<?php
2
/**
3
 * This file is part of graze/data-file
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/data-file/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/data-file
12
 */
13
14
namespace Graze\DataFile\Format\Parser;
15
16
use ArrayIterator;
17
use Graze\DataFile\Format\JsonFormatInterface;
18
use Graze\DataFile\Helper\LineStreamIterator;
19
use Graze\DataFile\Helper\MapIterator;
20
use Iterator;
21
use RuntimeException;
22
23
class JsonParser implements ParserInterface
24
{
25
    const JSON_DEFAULT_DEPTH = 512;
26
27
    /** @var JsonFormatInterface */
28
    private $format;
29
30
    /**
31
     * JsonFormatter constructor.
32
     *
33
     * @param JsonFormatInterface $format
34
     */
35 8
    public function __construct(JsonFormatInterface $format)
36
    {
37 8
        $this->format = $format;
38 8
    }
39
40
    /**
41
     * @param resource $stream
42
     *
43
     * @return Iterator
44
     */
45 7
    public function parse($stream)
46
    {
47 7
        if ($this->format->isEachLine()) {
48 4
            $iterator = new LineStreamIterator(
49
                $stream,
50
                [
51 4
                    LineStreamIterator::OPTION_ENDING         => "\n",
52 4
                    LineStreamIterator::OPTION_IGNORE_BLANK   => $this->format->isIgnoreBlankLines(),
53
                    LineStreamIterator::OPTION_INCLUDE_ENDING => false,
54
                ]
55
            );
56 4
            $iterator->setIgnoreBlank($this->format->isIgnoreBlankLines());
57 4
            return new MapIterator($iterator, [$this, 'decodeJson']);
58
        } else {
59 3
            $json = $this->decodeJson(stream_get_contents($stream));
60 3
            if (is_array($json)) {
61 2
                return new ArrayIterator($json);
62
            } else {
63 1
                throw new RuntimeException("Expecting a json array to parse, unknown format detected");
64
            }
65
        }
66
    }
67
68
    /**
69
     * @param string $string
70
     *
71
     * @return mixed
72
     */
73 6
    public function decodeJson($string)
74
    {
75 6
        return json_decode(
76
            $string,
77 6
            $this->format->isJsonDecodeAssoc(),
78 6
            static::JSON_DEFAULT_DEPTH,
79 6
            $this->format->getJsonDecodeOptions()
80
        );
81
    }
82
}
83