Passed
Push — master ( 612cc4...8ae96d )
by Viacheslav
01:31
created

Apply::setUpDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 2
dl 0
loc 10
ccs 9
cts 9
cp 1
crap 1
rs 9.4285
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
        parent::setUpDefinition($definition, $options);
27 1
        $definition->description = 'Apply patch to base json document, output to STDOUT';
28 1
        unset($options->originalPath);
29 1
        unset($options->newPath);
30
31 1
    }
32
33 1
    public function performAction()
34
    {
35 1
        if (!file_exists($this->patchPath)) {
36
            $this->response->error('File not found: ' . $this->patchPath);
37
            return;
38
        }
39 1
        if (!file_exists($this->basePath)) {
40
            $this->response->error('File not found: ' . $this->basePath);
41
            return;
42
        }
43
44 1
        $patchJson = file_get_contents($this->patchPath);
45 1
        if (!$patchJson) {
46
            $this->response->error('Unable to read ' . $this->patchPath);
47
            return;
48
        }
49
50 1
        $baseJson = file_get_contents($this->basePath);
51 1
        if (!$baseJson) {
52
            $this->response->error('Unable to read ' . $this->basePath);
53
            return;
54
        }
55
56
        try {
57 1
            $patch = JsonPatch::import(json_decode($patchJson));
58 1
            $base = json_decode($baseJson);
59 1
            $patch->apply($base);
60 1
            $this->out = $base;
61
        } catch (Exception $e) {
62
            $this->response->error($e->getMessage());
63
        }
64
65 1
        $this->postPerform();
66 1
    }
67
68
}