Patch::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
dl 0
loc 4
c 2
b 1
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace gamringer\JSONPatch;
5
6
use gamringer\JSONPointer;
7
use gamringer\JSONPointer\Pointer;
8
9
class Patch
10
{
11
    protected $operations = [];
12
13
    public static function fromJSON(string $patchContent)
14
    {
15
        $patch = new static();
16
17
        $patchContent = self::decodePatchContent($patchContent);
18
19
        foreach ($patchContent as $operationContent) {
20
            $operation = Operation::fromDecodedJSON($operationContent);
21
            $patch->addOperation($operation);
22
        }
23
24
        return $patch;
25
    }
26
27
    public function apply(&$target)
28
    {
29
        $jsonPointer = new Pointer($target);
30
        
31
        try {
32
            foreach ($this->operations as $i => $operation) {
33
                $operation->apply($jsonPointer);
34
            }
35
        } catch (Operation\Exception $e) {
36
            $this->revert($jsonPointer, $i);
37
38
            throw new Exception('An Operation failed', 1, $e);
39
        }
40
    }
41
42
    private function revert(Pointer $jsonPointer, $index)
43
    {
44
        $operations = array_reverse(array_slice($this->operations, 0, $index));
45
46
        try {
47
            foreach ($operations as $operation) {
48
                $operation->revert($jsonPointer);
49
            }
50
        } catch (Operation\Exception $e) {
51
            throw new Exception('An Operation failed and the reverting process also failed', 2, $e);
52
        }
53
    }
54
55
    public function addOperation(Operation\Atomic $operation)
56
    {
57
        $this->operations[] = $operation;
58
    }
59
60
    public function __toString()
61
    {
62
        return '['.implode(',', $this->operations).']';
63
    }
64
65
    private static function decodePatchContent($patchContent)
66
    {
67
        $patchContent = json_decode($patchContent);
68
        if (json_last_error() != JSON_ERROR_NONE) {
69
            throw new Exception('Content of source patch file could not be decoded', 3);
70
        }
71
72
        if (!is_array($patchContent)) {
73
            throw new Exception('Content of source patch file is not a collection', 4);
74
        }
75
76
        return $patchContent;
77
    }
78
}
79