Replace   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 50
c 5
b 1
f 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A apply() 0 10 2
A revert() 0 4 1
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;
9
10
class Replace extends Operation implements Atomic
11
{
12
    private $value;
13
    private $previousValue;
14
15
    public function __construct(string $path, $value)
16
    {
17
        $this->path = $path;
18
        $this->value = $value;
19
    }
20
21
    public function apply(Pointer $target)
22
    {
23
        try {
24
            $target->get($this->path);
25
        } catch (JSONPointer\Exception $e) {
26
            throw new Exception($e->getMessage(), 0, $e);
27
        }
28
        
29
        $this->previousValue = $target->set($this->path, $this->value);
30
    }
31
32
    public function revert(Pointer $target)
33
    {
34
        $target->set($this->path, $this->previousValue);
35
    }
36
37
    public static function fromDecodedJSON($operationContent): self
38
    {
39
        self::assertValidOperationContent($operationContent);
40
41
        return new self($operationContent->path, $operationContent->value);
42
    }
43
44
    private static function assertValidOperationContent($operationContent)
45
    {
46
        if (!property_exists($operationContent, 'path') || !property_exists($operationContent, 'value')) {
47
            throw new Operation\Exception('"Replace" Operations must contain a "path" and "value" member');
48
        }
49
    }
50
51
    public function __toString(): string
52
    {
53
        return json_encode([
54
            'op' => Operation::OP_REPLACE,
55
            'path' => $this->path,
56
            'value' => $this->value,
57
        ]);
58
    }
59
}
60