Completed
Push — master ( 526a15...c763be )
by Viacheslav
01:41
created

Apply::performAction()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 9.3798

Importance

Changes 0
Metric Value
cc 6
eloc 22
nc 8
nop 0
dl 0
loc 33
ccs 12
cts 22
cp 0.5455
crap 9.3798
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace Swaggest\JsonCli;
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 1
    static function setUpDefinition(Definition $definition, $options)
21
    {
22 1
        $options->patchPath = Command\Option::create()->setType()->setIsUnnamed()
23 1
            ->setDescription('Path to JSON patch file');
24 1
        $options->basePath = Command\Option::create()->setType()->setIsUnnamed()
25 1
            ->setDescription('Path to JSON base file');
26 1
        $options->pretty = Command\Option::create()
27 1
            ->setDescription('Pretty-print result JSON');
28 1
        $options->rearrangeArrays = Command\Option::create()
29 1
            ->setDescription('Rearrange arrays to match original');
30 1
        $definition->description = 'Apply patch to base json document, output to STDOUT';
31
32 1
    }
33
34 1
    public function performAction()
35
    {
36 1
        if (!file_exists($this->patchPath)) {
37
            $this->response->error('File not found: ' . $this->patchPath);
38
            return;
39
        }
40 1
        if (!file_exists($this->basePath)) {
41
            $this->response->error('File not found: ' . $this->basePath);
42
            return;
43
        }
44
45 1
        $patchJson = file_get_contents($this->patchPath);
46 1
        if (!$patchJson) {
47
            $this->response->error('Unable to read ' . $this->patchPath);
48
            return;
49
        }
50
51 1
        $baseJson = file_get_contents($this->basePath);
52 1
        if (!$baseJson) {
53
            $this->response->error('Unable to read ' . $this->basePath);
54
            return;
55
        }
56
57
        try {
58 1
            $patch = JsonPatch::import(json_decode($patchJson));
59 1
            $base = json_decode($baseJson);
60 1
            $patch->apply($base);
61 1
            $this->out = $base;
62
        } catch (Exception $e) {
63
            $this->response->error($e->getMessage());
64
        }
65
66 1
        $this->postPerform();
67 1
    }
68
69
}