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 Copy 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
|
|
|
$copiedValue = $target->get($this->from); |
27
|
|
|
$this->previousValue = $target->insert($this->path, $copiedValue); |
28
|
|
|
} catch (JSONPointer\Exception $e) { |
29
|
|
|
throw new Exception($e->getMessage(), 0, $e); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function revert(Pointer $target) |
34
|
|
|
{ |
35
|
|
|
$target->remove($this->path); |
36
|
|
|
if (!($this->previousValue instanceof VoidValue)) { |
37
|
|
|
$target->insert($this->path, $this->previousValue); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public static function fromDecodedJSON($operationContent): self |
42
|
|
|
{ |
43
|
|
|
self::assertValidOperationContent($operationContent); |
44
|
|
|
|
45
|
|
|
return new self($operationContent->path, $operationContent->from); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private static function assertValidOperationContent($operationContent) |
49
|
|
|
{ |
50
|
|
|
if (!property_exists($operationContent, 'path') || !property_exists($operationContent, 'from')) { |
51
|
|
|
throw new Operation\Exception('"Copy" Operations must contain a "from" and "path" member'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// Validate that the "path" doesn't contain "from" |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function __toString(): string |
58
|
|
|
{ |
59
|
|
|
return json_encode([ |
60
|
|
|
'op' => Operation::OP_COPY, |
61
|
|
|
'path' => $this->path, |
62
|
|
|
'from' => $this->from, |
63
|
|
|
]); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|