-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPatch.php
More file actions
78 lines (61 loc) · 2.01 KB
/
Copy pathPatch.php
File metadata and controls
78 lines (61 loc) · 2.01 KB
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
<?php
declare(strict_types=1);
namespace gamringer\JSONPatch;
use gamringer\JSONPointer;
use gamringer\JSONPointer\Pointer;
class Patch
{
protected $operations = [];
public static function fromJSON(string $patchContent)
{
$patch = new static();
$patchContent = self::decodePatchContent($patchContent);
foreach ($patchContent as $operationContent) {
$operation = Operation::fromDecodedJSON($operationContent);
$patch->addOperation($operation);
}
return $patch;
}
public function apply(&$target)
{
$jsonPointer = new Pointer($target);
try {
foreach ($this->operations as $i => $operation) {
$operation->apply($jsonPointer);
}
} catch (Operation\Exception $e) {
$this->revert($jsonPointer, $i);
throw new Exception('An Operation failed', 1, $e);
}
}
private function revert(Pointer $jsonPointer, $index)
{
$operations = array_reverse(array_slice($this->operations, 0, $index));
try {
foreach ($operations as $operation) {
$operation->revert($jsonPointer);
}
} catch (Operation\Exception $e) {
throw new Exception('An Operation failed and the reverting process also failed', 2, $e);
}
}
public function addOperation(Operation\Atomic $operation)
{
$this->operations[] = $operation;
}
public function __toString()
{
return '['.implode(',', $this->operations).']';
}
private static function decodePatchContent($patchContent)
{
$patchContent = json_decode($patchContent);
if (json_last_error() != JSON_ERROR_NONE) {
throw new Exception('Content of source patch file could not be decoded', 3);
}
if (!is_array($patchContent)) {
throw new Exception('Content of source patch file is not a collection', 4);
}
return $patchContent;
}
}