Passed
Pull Request — master (#42)
by Viacheslav
02:53 queued 10s
created

AssociativeTest   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 41
c 1
b 0
f 0
dl 0
loc 52
rs 10
wmc 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A testDiffAssociative() 0 47 1
1
<?php
2
3
namespace Swaggest\JsonDiff\Tests;
4
5
6
use Swaggest\JsonDiff\JsonDiff;
7
use Swaggest\JsonDiff\JsonPatch;
8
9
class AssociativeTest extends \PHPUnit_Framework_TestCase
10
{
11
    /**
12
     * @throws \Swaggest\JsonDiff\Exception
13
     */
14
    public function testDiffAssociative()
15
    {
16
        $originalJson = <<<'JSON'
17
{
18
    "key1": [4, 1, 2, 3],
19
    "key2": 2,
20
    "key3": {
21
        "sub0": 0,
22
        "sub1": "a",
23
        "sub2": "b"
24
    },
25
    "key4": [
26
        {"a":1, "b":true, "subs": [{"s":1}, {"s":2}, {"s":3}]}, {"a":2, "b":false}, {"a":3}
27
    ]
28
}
29
JSON;
30
31
        $newJson = <<<'JSON'
32
{
33
    "key5": "wat",
34
    "key1": [5, 1, 2, 3],
35
    "key4": [
36
        {"c":false, "a":2}, {"a":1, "b":true, "subs": [{"s":3, "add": true}, {"s":2}, {"s":1}]}, {"c":1, "a":3}
37
    ],
38
    "key3": {
39
        "sub3": 0,
40
        "sub2": false,
41
        "sub1": "c"
42
    }
43
}
44
JSON;
45
46
        $diff = new JsonDiff(json_decode($originalJson), json_decode($newJson));
47
        $expected = json_encode($diff->getPatch()->jsonSerialize(), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES);
48
49
        $diff = new JsonDiff(json_decode($originalJson, true), json_decode($newJson, true),
50
            JsonDiff::TOLERATE_ASSOCIATIVE_ARRAYS);
51
        $actual = json_encode($diff->getPatch()->jsonSerialize(), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES);
52
53
        $this->assertEquals($expected, $actual);
54
55
        $original = json_decode($originalJson, true);
56
        $newJson = json_decode($newJson, true);
57
        $patch = JsonPatch::import(json_decode($actual, true));
58
        $patch->setFlags(JsonPatch::TOLERATE_ASSOCIATIVE_ARRAYS);
59
        $patch->apply($original);
60
        $this->assertEquals($newJson, $original);
61
    }
62
}