Passed
Pull Request — master (#18)
by
unknown
04:16
created

JsonDiff::getRemovedCnt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Swaggest\JsonDiff;
4
5
use Swaggest\JsonDiff\JsonPatch\Add;
6
use Swaggest\JsonDiff\JsonPatch\Remove;
7
use Swaggest\JsonDiff\JsonPatch\Replace;
8
use Swaggest\JsonDiff\JsonPatch\Test;
9
10
class JsonDiff
11
{
12
    /**
13
     * REARRANGE_ARRAYS is an option to enable arrays rearrangement to minimize the difference.
14
     */
15
    const REARRANGE_ARRAYS = 1;
16
17
    /**
18
     * STOP_ON_DIFF is an option to improve performance by stopping comparison when a difference is found.
19
     */
20
    const STOP_ON_DIFF = 2;
21
22
    /**
23
     * JSON_URI_FRAGMENT_ID is an option to use URI Fragment Identifier Representation (example: "#/c%25d").
24
     * If not set default JSON String Representation (example: "/c%d").
25
     */
26
    const JSON_URI_FRAGMENT_ID = 4;
27
28
    /**
29
     * SKIP_JSON_PATCH is an option to improve performance by not building JsonPatch for this diff.
30
     */
31
    const SKIP_JSON_PATCH = 8;
32
33
    /**
34
     * SKIP_JSON_MERGE_PATCH is an option to improve performance by not building JSON Merge Patch value for this diff.
35
     */
36
    const SKIP_JSON_MERGE_PATCH = 16;
37
38
    private $options = 0;
39
    private $original;
40
    private $new;
41
42
    /**
43
     * @var mixed Merge patch container
44
     */
45
    private $merge;
46
47
    private $added;
48
    private $addedCnt = 0;
49
    private $addedPaths = array();
50
51
    private $removed;
52
    private $removedCnt = 0;
53
    private $removedPaths = array();
54
55
    private $modifiedOriginal;
56
    private $modifiedNew;
57
    private $modifiedCnt = 0;
58
    private $modifiedPaths = array();
59
    private $modifiedFull = [];
60
61
    private $path = '';
62
    private $pathItems = array();
63
64
    private $rearranged;
65
66
    /** @var JsonPatch */
67
    private $jsonPatch;
68
69
    /**
70
     * @param mixed $original
71
     * @param mixed $new
72
     * @param int $options
73
     * @throws Exception
74
     */
75 47
    public function __construct($original, $new, $options = 0)
76
    {
77 47
        if (!($options & self::SKIP_JSON_PATCH)) {
78 47
            $this->jsonPatch = new JsonPatch();
79
        }
80
81 47
        $this->original = $original;
82 47
        $this->new = $new;
83 47
        $this->options = $options;
84
85 47
        if ($options & self::JSON_URI_FRAGMENT_ID) {
86 1
            $this->path = '#';
87
        }
88
89 47
        $this->rearranged = $this->rearrange();
90 47
        if (($new !== null) && $this->merge === null) {
91 19
            $this->merge = new \stdClass();
92
        }
93 47
    }
94
95
    /**
96
     * Returns total number of differences
97
     * @return int
98
     */
99 20
    public function getDiffCnt()
100
    {
101 20
        return $this->addedCnt + $this->modifiedCnt + $this->removedCnt;
102
    }
103
104
    /**
105
     * Returns removals as partial value of original.
106
     * @return mixed
107
     */
108 4
    public function getRemoved()
109
    {
110 4
        return $this->removed;
111
    }
112
113
    /**
114
     * Returns list of `JSON` paths that were removed from original.
115
     * @return array
116
     */
117 4
    public function getRemovedPaths()
118
    {
119 4
        return $this->removedPaths;
120
    }
121
122
    /**
123
     * Returns number of removals.
124
     * @return int
125
     */
126 4
    public function getRemovedCnt()
127
    {
128 4
        return $this->removedCnt;
129
    }
130
131
    /**
132
     * Returns additions as partial value of new.
133
     * @return mixed
134
     */
135 1
    public function getAdded()
136
    {
137 1
        return $this->added;
138
    }
139
140
    /**
141
     * Returns number of additions.
142
     * @return int
143
     */
144 1
    public function getAddedCnt()
145
    {
146 1
        return $this->addedCnt;
147
    }
148
149
    /**
150
     * Returns list of `JSON` paths that were added to new.
151
     * @return array
152
     */
153 1
    public function getAddedPaths()
154
    {
155 1
        return $this->addedPaths;
156
    }
157
158
    /**
159
     * Returns changes as partial value of original.
160
     * @return mixed
161
     */
162 1
    public function getModifiedOriginal()
163
    {
164 1
        return $this->modifiedOriginal;
165
    }
166
167
    /**
168
     * Returns changes as partial value of new.
169
     * @return mixed
170
     */
171 1
    public function getModifiedNew()
172
    {
173 1
        return $this->modifiedNew;
174
    }
175
176
    /**
177
     * Returns number of changes.
178
     * @return int
179
     */
180 2
    public function getModifiedCnt()
181
    {
182 2
        return $this->modifiedCnt;
183
    }
184
185
    /**
186
     * Returns list of `JSON` paths that were changed from original to new.
187
     * @return array
188
     */
189 1
    public function getModifiedPaths()
190
    {
191 1
        return $this->modifiedPaths;
192
    }
193
194
    /**
195
     * @return array
196
     */
197
    public function getModifiedFull()
198
    {
199
        return $this->modifiedFull;
200
    }
201
202
    /**
203
     * Returns new value, rearranged with original order.
204
     * @return array|object
205
     */
206 3
    public function getRearranged()
207
    {
208 3
        return $this->rearranged;
209
    }
210
211
    /**
212
     * Returns JsonPatch of difference
213
     * @return JsonPatch
214
     */
215 6
    public function getPatch()
216
    {
217 6
        return $this->jsonPatch;
218
    }
219
220
    /**
221
     * Returns JSON Merge Patch value of difference
222
     */
223 19
    public function getMergePatch()
224
    {
225 19
        return $this->merge;
226
227
    }
228
229
    /**
230
     * @return array|null|object|\stdClass
231
     * @throws Exception
232
     */
233 47
    private function rearrange()
234
    {
235 47
        return $this->process($this->original, $this->new);
236
    }
237
238
    /**
239
     * @param mixed $original
240
     * @param mixed $new
241
     * @return array|null|object|\stdClass
242
     * @throws Exception
243
     */
244 47
    private function process($original, $new)
245
    {
246 47
        $merge = !($this->options & self::SKIP_JSON_MERGE_PATCH);
247
248
        if (
249 47
            (!$original instanceof \stdClass && !is_array($original))
250 47
            || (!$new instanceof \stdClass && !is_array($new))
251
        ) {
252 39
            if ($original !== $new) {
253 20
                $this->modifiedCnt++;
254 20
                if ($this->options & self::STOP_ON_DIFF) {
255 4
                    return null;
256
                }
257 16
                $this->modifiedPaths [] = $this->path;
258
259 16
                if ($this->jsonPatch !== null) {
260 16
                    $this->jsonPatch->op(new Test($this->path, $original));
261 16
                    $this->jsonPatch->op(new Replace($this->path, $new));
262
                }
263
264 16
                JsonPointer::add($this->modifiedOriginal, $this->pathItems, $original);
265 16
                JsonPointer::add($this->modifiedNew, $this->pathItems, $new);
266
267 16
                if ($merge) {
268 16
                    JsonPointer::add($this->merge, $this->pathItems, $new, JsonPointer::RECURSIVE_KEY_CREATION);
269
                }
270
271 16
                $this->modifiedFull[] = [
272 16
                    'path' => $this->path,
273 16
                    'new' => $new,
274 16
                    'original' => $original,
275
                ];
276
            }
277 35
            return $new;
278
        }
279
280
        if (
281 37
            ($this->options & self::REARRANGE_ARRAYS)
282 37
            && is_array($original) && is_array($new)
283
        ) {
284 5
            $new = $this->rearrangeArray($original, $new);
285
        }
286
287 37
        $newArray = $new instanceof \stdClass ? get_object_vars($new) : $new;
288 37
        $newOrdered = array();
289
290 37
        $originalKeys = $original instanceof \stdClass ? get_object_vars($original) : $original;
291 37
        $isArray = is_array($original);
292 37
        $removedOffset = 0;
293
294 37
        if ($merge && is_array($new) && !is_array($original)) {
295 2
            $merge = false;
296 2
            JsonPointer::add($this->merge, $this->pathItems, $new);
297 35
        } elseif ($merge  && $new instanceof \stdClass && !$original instanceof \stdClass) {
298 4
            $merge = false;
299 4
            JsonPointer::add($this->merge, $this->pathItems, $new);
300
        }
301
302 37
        $isUriFragment = (bool)($this->options & self::JSON_URI_FRAGMENT_ID);
303 37
        foreach ($originalKeys as $key => $originalValue) {
304 36
            if ($this->options & self::STOP_ON_DIFF) {
305 7
                if ($this->modifiedCnt || $this->addedCnt || $this->removedCnt) {
306 1
                    return null;
307
                }
308
            }
309
310 36
            $path = $this->path;
311 36
            $pathItems = $this->pathItems;
312 36
            $actualKey = $key;
313 36
            if ($isArray && is_int($actualKey)) {
314 16
                $actualKey -= $removedOffset;
315
            }
316 36
            $this->path .= '/' . JsonPointer::escapeSegment((string)$actualKey, $isUriFragment);
317 36
            $this->pathItems[] = $actualKey;
318
319 36
            if (array_key_exists($key, $newArray)) {
320 30
                $newOrdered[$key] = $this->process($originalValue, $newArray[$key]);
321 30
                unset($newArray[$key]);
322
            } else {
323 18
                $this->removedCnt++;
324 18
                if ($this->options & self::STOP_ON_DIFF) {
325 2
                    return null;
326
                }
327 16
                $this->removedPaths [] = $this->path;
328 16
                if ($isArray) {
329 4
                    $removedOffset++;
330
                }
331
332 16
                if ($this->jsonPatch !== null) {
333 16
                    $this->jsonPatch->op(new Remove($this->path));
334
                }
335
336 16
                JsonPointer::add($this->removed, $this->pathItems, $originalValue);
337 16
                if ($merge) {
338 13
                    JsonPointer::add($this->merge, $this->pathItems, null);
339
                }
340
341
            }
342 35
            $this->path = $path;
343 35
            $this->pathItems = $pathItems;
344
        }
345
346
        // additions
347 35
        foreach ($newArray as $key => $value) {
348 15
            $this->addedCnt++;
349 15
            if ($this->options & self::STOP_ON_DIFF) {
350 2
                return null;
351
            }
352 13
            $newOrdered[$key] = $value;
353 13
            $path = $this->path . '/' . JsonPointer::escapeSegment($key, $isUriFragment);
354 13
            $pathItems = $this->pathItems;
355 13
            $pathItems[] = $key;
356 13
            JsonPointer::add($this->added, $pathItems, $value);
357 13
            if ($merge) {
358 9
                JsonPointer::add($this->merge, $pathItems, $value);
359
            }
360
361 13
            $this->addedPaths [] = $path;
362
363 13
            if ($this->jsonPatch !== null) {
364 13
                $this->jsonPatch->op(new Add($path, $value));
365
            }
366
367
        }
368
369 35
        return is_array($new) ? $newOrdered : (object)$newOrdered;
370
    }
371
372 5
    private function rearrangeArray(array $original, array $new)
373
    {
374 5
        $first = reset($original);
375 5
        if (!$first instanceof \stdClass) {
376 3
            return $new;
377
        }
378
379 4
        $uniqueKey = false;
380 4
        $uniqueIdx = array();
381
382
        // find unique key for all items
383
        /** @var mixed[string]  $f */
384 4
        $f = get_object_vars($first);
385 4
        foreach ($f as $key => $value) {
386 4
            if (is_array($value) || $value instanceof \stdClass) {
387
                continue;
388
            }
389
390 4
            $keyIsUnique = true;
391 4
            $uniqueIdx = array();
392 4
            foreach ($original as $item) {
393 4
                if (!$item instanceof \stdClass) {
394
                    return $new;
395
                }
396 4
                if (!isset($item->$key)) {
397
                    $keyIsUnique = false;
398
                    break;
399
                }
400 4
                $value = $item->$key;
401 4
                if ($value instanceof \stdClass || is_array($value)) {
402
                    $keyIsUnique = false;
403
                    break;
404
                }
405
406 4
                if (isset($uniqueIdx[$value])) {
407
                    $keyIsUnique = false;
408
                    break;
409
                }
410 4
                $uniqueIdx[$value] = true;
411
            }
412
413 4
            if ($keyIsUnique) {
414 4
                $uniqueKey = $key;
415 4
                break;
416
            }
417
        }
418
419 4
        if ($uniqueKey) {
0 ignored issues
show
introduced by
$uniqueKey is of type mixed, thus it always evaluated to false.
Loading history...
420 4
            $newIdx = array();
421 4
            foreach ($new as $item) {
422 4
                if (!$item instanceof \stdClass) {
423
                    return $new;
424
                }
425
426 4
                if (!property_exists($item, $uniqueKey)) {
427
                    return $new;
428
                }
429
430 4
                $value = $item->$uniqueKey;
431
432 4
                if ($value instanceof \stdClass || is_array($value)) {
433
                    return $new;
434
                }
435
436 4
                if (isset($newIdx[$value])) {
437
                    return $new;
438
                }
439
440 4
                $newIdx[$value] = $item;
441
            }
442
443 4
            $newRearranged = array();
444 4
            foreach ($uniqueIdx as $key => $item) {
445 4
                if (isset($newIdx[$key])) {
446 4
                    $newRearranged [] = $newIdx[$key];
447 4
                    unset($newIdx[$key]);
448
                }
449
            }
450 4
            foreach ($newIdx as $item) {
451
                $newRearranged [] = $item;
452
            }
453 4
            return $newRearranged;
454
        }
455
456
        return $new;
457
    }
458
}