This repository has been archived by the owner on Feb 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonIteratorTest.php
83 lines (63 loc) · 2.8 KB
/
JsonIteratorTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/*
* @author Etienne Lamoureux <etienne.lamoureux@crystalgorithm.com>
* @copyright 2014 Etienne Lamoureux
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
*/
namespace Crystalgorithm\PhpJsonIterator\Iterators;
use PHPUnit_Framework_TestCase;
use Crystalgorithm\PhpJsonIterator\JsonIteratorFactory;
final class JsonIteratorTest extends PHPUnit_Framework_TestCase {
const FLAT_JSON_OBJECT_AS_STRING = '{"foo":"bar","fizz":"buzz"}';
const NESTED_JSON_OBJECT_AS_STRING = '{"foo":"bar","fizz":{"id":1,"nested":true}}';
protected $counter;
protected function setUp() {
$this->counter = 0;
}
/**
* If you're dealing with flat JSON objects (no nested objects), you can
* build the iterator with no addiitonal parameters.
*/
public function testGivenJsonArrayOfFlatObjectsThenParseOneByOne() {
$json = $this::buildTestJson(5, self::FLAT_JSON_OBJECT_AS_STRING);
$iterator = JsonIteratorFactory::buildJsonIterator($json);
$this->goThroughIterator($iterator);
$this->assertEquals(5, $this->counter);
}
/**
* If you're dealing with JSON objects that contain nested JSON objects,
* you have to provide the first key of the top-level object as an
* additional parameter.
* If your collection of objects does not have a standard schema, or fields
* are listed in a random order, this project cannot help you.
*/
public function testGivenJsonArrayOfNestedObjectsThenParseOneByOne() {
$json = $this::buildTestJson(5, self::NESTED_JSON_OBJECT_AS_STRING);
$iterator = JsonIteratorFactory::buildJsonIterator($json, array("firstTopLevelString" => "foo"));
$this->goThroughIterator($iterator);
$this->assertEquals(5, $this->counter);
}
/**
* The iterator supports incorrect JSON arrays (with no start nor end brackets).
*/
public function testCommaSeparatedJsonObjectsThenParseOneByOne() {
$jsonObjects = array_fill(0, 5, self::FLAT_JSON_OBJECT_AS_STRING);
$json = implode(",", $jsonObjects);
$iterator = JsonIteratorFactory::buildJsonIterator($json, array("jsonHasSquareBrackets" => false));
$this->goThroughIterator($iterator);
$this->assertEquals(5, $this->counter);
}
protected static function buildTestJson($nbObjects, $jsonObject) {
$jsonObjects = array_fill(0, $nbObjects, $jsonObject);
$json = implode(",", $jsonObjects);
return "[" . $json . "]";
}
protected function goThroughIterator($iterator) {
foreach ($iterator as $parsedJsonObject) {
// Here you can do something with $parsedJsonObject as an array.
// It has been "json_decoded" already.
//print_r($parsedJsonObject);
$this->counter++;
}
}
}