Replace::setUpDefinition()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 11
ccs 10
cts 10
cp 1
crap 1
rs 9.9666
1
<?php
2
3
namespace Swaggest\JsonCli;
4
5
use Swaggest\JsonDiff\JsonValueReplace;
6
use Symfony\Component\Yaml\Yaml;
7
use Yaoi\Command;
8
9
class Replace extends Base
10
{
11
    public $path;
12
13
    public $search;
14
    public $replace;
15
    public $pathFilter;
16
17
    /**
18
     * @param Command\Definition $definition
19
     * @param \stdClass|static $options
20
     */
21 1
    static function setUpDefinition(Command\Definition $definition, $options)
22
    {
23 1
        $options->path = Command\Option::create()->setIsUnnamed()->setIsRequired()
24 1
            ->setDescription('Path to JSON/YAML file');
25 1
        $options->search = Command\Option::create()->setIsUnnamed()->setIsRequired()
26 1
            ->setDescription('Search JSON value');
27 1
        $options->replace = Command\Option::create()->setIsUnnamed()->setIsRequired()
28 1
            ->setDescription('Replace JSON value');
29 1
        $options->pathFilter = Command\Option::create()->setType()
30 1
            ->setDescription('JSON path filter regex, example "/definitions/.*/properties/deletedAt"');
31 1
        $definition->description = 'Minify JSON document';
32 1
    }
33
34 1
    public function performAction()
35
    {
36 1
        $jsonData = $this->readData($this->path);
37
38 1
        $search = json_decode($this->search);
39 1
        if (json_last_error()) {
40
            $this->response->error('Invalid JSON: ' . $this->search);
41
            return;
42
        }
43 1
        $replace = json_decode($this->replace);
44 1
        if (json_last_error()) {
45
            $this->response->error('Invalid JSON: ' . $this->replace);
46
            return;
47
        }
48
49 1
        $pathFilter = null;
50 1
        if ($this->pathFilter) {
51 1
            $pathFilter = '|' . $this->pathFilter . '|';
52
        }
53
54 1
        $replacer = new JsonValueReplace($search, $replace, $pathFilter);
55 1
        $this->out = $replacer->process($jsonData);
56 1
        $this->postPerform();
57 1
    }
58
59
}