Move   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
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 56
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 10 2
A fromDecodedJSON() 0 6 1
A assertValidOperationContent() 0 6 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 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