Copy   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 6
Bugs 2 Features 1
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 55
c 6
b 2
f 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A apply() 0 9 2
A revert() 0 7 2
A fromDecodedJSON() 0 6 1
A assertValidOperationContent() 0 8 3
A __toString() 0 8 1
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