1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace gamringer\JSONPatch\Operation; |
5
|
|
|
|
6
|
|
|
use gamringer\JSONPatch\Operation; |
7
|
|
|
use gamringer\JSONPointer\Pointer; |
8
|
|
|
use gamringer\JSONPointer\VoidValue; |
9
|
|
|
use gamringer\JSONPointer; |
10
|
|
|
|
11
|
|
|
class Move extends Operation implements Atomic |
12
|
|
|
{ |
13
|
|
|
private $from = ''; |
14
|
|
|
|
15
|
|
|
private $previousValue; |
16
|
|
|
|
17
|
|
|
public function __construct(string $path, string $from) |
18
|
|
|
{ |
19
|
|
|
$this->path = $path; |
20
|
|
|
$this->from = $from; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function apply(Pointer $target) |
24
|
|
|
{ |
25
|
|
|
try { |
26
|
|
|
$movedValue = $target->remove($this->from); |
27
|
|
|
$this->previousValue = $target->insert($this->path, $movedValue); |
28
|
|
|
} catch (JSONPointer\Exception $e) { |
29
|
|
|
throw new Exception($e->getMessage(), 0, $e); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function revert(Pointer $target) |
34
|
|
|
{ |
35
|
|
|
$movedValue = $target->remove($this->path); |
36
|
|
|
|
37
|
|
|
if (!($this->previousValue instanceof VoidValue)) { |
38
|
|
|
$target->insert($this->path, $this->previousValue); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$target->insert($this->from, $movedValue); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public static function fromDecodedJSON($operationContent): self |
45
|
|
|
{ |
46
|
|
|
self::assertValidOperationContent($operationContent); |
47
|
|
|
|
48
|
|
|
return new self($operationContent->path, $operationContent->from); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private static function assertValidOperationContent($operationContent) |
52
|
|
|
{ |
53
|
|
|
if (!property_exists($operationContent, 'path') || !property_exists($operationContent, 'from')) { |
54
|
|
|
throw new Operation\Exception('"Move" Operations must contain a "from" and "path" member'); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function __toString(): string |
59
|
|
|
{ |
60
|
|
|
return json_encode([ |
61
|
|
|
'op' => Operation::OP_MOVE, |
62
|
|
|
'path' => $this->path, |
63
|
|
|
'from' => $this->from, |
64
|
|
|
]); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|