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
|
|
|
|