Completed
Push — master ( d6e24f...c5cb7d )
by Viacheslav
02:06
created

Base::prePerform()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.7458

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 6
nop 0
dl 0
loc 26
ccs 10
cts 17
cp 0.5881
crap 6.7458
rs 8.439
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A Base::postPerform() 0 17 4
1
<?php
2
3
namespace Swaggest\JsonCli;
4
5
6
use Symfony\Component\Yaml\Yaml;
7
use Yaoi\Command;
8
9
abstract class Base extends Command
10
{
11
    public $pretty;
12
    public $toYaml;
13
    public $output;
14
15 1
    static function setUpDefinition(Command\Definition $definition, $options)
16
    {
17 1
        $options->pretty = Command\Option::create()
18 1
            ->setDescription('Pretty-print result JSON');
19 1
        $options->output = Command\Option::create()->setType()
20 1
            ->setDescription('Path to output result, default STDOUT');
21 1
        $options->toYaml = Command\Option::create()->setDescription('Output in YAML format');
22 1
    }
23
24
25
    protected $out;
26
27 5
    protected function readData($path)
28
    {
29 5
        if (!file_exists($path)) {
30
            $this->response->error('Unable to find ' . $path);
31
            die(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
32
        }
33 5
        $fileData = file_get_contents($path);
34 5
        if (!$fileData) {
35
            $this->response->error('Unable to read ' . $path);
36
            die(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
37
        }
38 5
        if (substr($path, -5) === '.yaml' || substr($path, -4) === '.yml') {
39
            $jsonData = Yaml::parse($fileData, Yaml::PARSE_OBJECT);
40
        } else {
41 5
            $jsonData = json_decode($fileData);
42
        }
43
44 5
        return $jsonData;
45
    }
46
47 8
    protected function postPerform()
48
    {
49 8
        $options = JSON_UNESCAPED_SLASHES;
50 8
        if ($this->pretty) {
51 5
            $options += JSON_PRETTY_PRINT;
52
        }
53
54 8
        if ($this->toYaml) {
55
            $result = Yaml::dump($this->out, 2, 2, Yaml::DUMP_OBJECT_AS_MAP);
56
        } else {
57 8
            $result = json_encode($this->out, $options);
58
        }
59
60 8
        if ($this->output) {
61
            file_put_contents($this->output, $result);
62
        } else {
63 8
            echo $result;
64
        }
65
    }
66
}