Completed
Pull Request — master (#3)
by Harry
03:17
created

JsonParser::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
ccs 14
cts 14
cp 1
rs 9.2
cc 3
eloc 15
nc 3
nop 1
crap 3
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 Psr\Http\Message\StreamInterface;
22
use RuntimeException;
23
24
class JsonParser implements ParserInterface
25
{
26
    const JSON_DEFAULT_DEPTH = 512;
27
28
    /**
29
     * @var JsonFormatInterface
30
     */
31
    private $format;
32
33
    /**
34
     * JsonFormatter constructor.
35
     *
36
     * @param JsonFormatInterface $format
37
     */
38 6
    public function __construct(JsonFormatInterface $format)
39
    {
40 6
        $this->format = $format;
41 6
    }
42
43
    /**
44
     * @param StreamInterface $stream
45
     *
46
     * @return Iterator
47
     */
48 6
    public function parse(StreamInterface $stream)
49
    {
50 6
        if ($this->format->isEachLine()) {
51 3
            $iterator = new LineStreamIterator(
52 3
                $stream,
53
                [
54 3
                    LineStreamIterator::OPTION_ENDING         => "\n",
55 3
                    LineStreamIterator::OPTION_IGNORE_BLANK   => $this->format->isIgnoreBlankLines(),
56 3
                    LineStreamIterator::OPTION_INCLUDE_ENDING => false,
57
                ]
58 3
            );
59 3
            $iterator->setIgnoreBlank($this->format->isIgnoreBlankLines());
60 3
            return new MapIterator($iterator, [$this, 'decodeJson']);
61
        } else {
62 3
            $json = $this->decodeJson($stream->getContents());
63 3
            if (is_array($json)) {
64 2
                return new ArrayIterator($json);
65
            } else {
66 1
                throw new RuntimeException("Expecting a json array to parse, unknown format detected");
67
            }
68
        }
69
    }
70
71
    /**
72
     * @param string $string
73
     *
74
     * @return mixed
75
     */
76 6
    public function decodeJson($string)
77
    {
78 6
        return json_decode(
79 6
            $string,
80 6
            $this->format->isJsonDecodeAssoc(),
81 6
            static::JSON_DEFAULT_DEPTH,
82 6
            $this->format->getJsonDecodeOptions()
83 6
        );
84
    }
85
}
86