Passed
Push — master ( 7ad944...9954d6 )
by Viacheslav
02:21
created

Apply   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 48
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setUpDefinition() 0 11 1
B performAction() 0 24 4
1
<?php
2
3
namespace Swaggest\JsonDiff\Cli;
4
5
use Swaggest\JsonDiff\Exception;
6
use Swaggest\JsonDiff\JsonPatch;
7
use Yaoi\Command;
8
use Yaoi\Command\Definition;
9
10
class Apply extends Base
11
{
12
    public $patchPath;
13
    public $basePath;
14
    public $isURIFragmentId = false;
15
16
    /**
17
     * @param Definition $definition
18
     * @param \stdClass|static $options
19
     */
20
    static function setUpDefinition(Definition $definition, $options)
21
    {
22
        $options->patchPath = Command\Option::create()->setType()->setIsUnnamed()
23
            ->setDescription('Path to JSON patch file');
24
        $options->basePath = Command\Option::create()->setType()->setIsUnnamed()
25
            ->setDescription('Path to JSON base file');
26
        $options->pretty = Command\Option::create()
27
            ->setDescription('Pretty-print result JSON');
28
        $options->rearrangeArrays = Command\Option::create()
29
            ->setDescription('Rearrange arrays to match original');
30
        $definition->description = 'Apply patch to base json document, output to STDOUT';
31
32
    }
33
34
    public function performAction()
35
    {
36
        $patchJson = file_get_contents($this->patchPath);
37
        if (!$patchJson) {
38
            $this->response->error('Unable to read ' . $this->patchPath);
39
            return;
40
        }
41
42
        $baseJson = file_get_contents($this->basePath);
43
        if (!$baseJson) {
44
            $this->response->error('Unable to read ' . $this->basePath);
45
            return;
46
        }
47
48
        try {
49
            $patch = JsonPatch::import(json_decode($patchJson));
50
            $base = json_decode($baseJson);
51
            $patch->apply($base);
52
        } catch (Exception $e) {
53
            $this->response->error($e->getMessage());
54
        }
55
        $this->out = $base;
56
57
        $this->postPerform();
58
    }
59
60
}