Completed
Push — master ( 8ae96d...916040 )
by Viacheslav
02:08
created

PrettyPrint::setUpDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 0
loc 8
ccs 7
cts 7
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Swaggest\JsonCli;
4
5
use Symfony\Component\Yaml\Yaml;
6
use Yaoi\Command;
7
use Yaoi\Command\Definition;
8
9
class PrettyPrint extends Command
10
{
11
    public $path;
12
    public $toYaml;
13
    public $output;
14
15
    /**
16
     * @param Definition $definition
17
     * @param \stdClass|static $options
18
     */
19 1
    static function setUpDefinition(Definition $definition, $options)
20
    {
21 1
        $options->path = Command\Option::create()->setIsUnnamed()->setIsRequired()
22 1
            ->setDescription('Path to JSON/YAML file');
23 1
        $options->toYaml = Command\Option::create()->setDescription('Output in YAML format');
24 1
        $options->output = Command\Option::create()->setType()
25 1
            ->setDescription('Path to output result, default STDOUT');
26 1
        $definition->description = 'Pretty print JSON document';
27 1
    }
28
29
    public function performAction()
30
    {
31
        $fileData = file_get_contents($this->path);
32
        if (!$fileData) {
33
            $this->response->error('Unable to read ' . $this->path);
34
            return;
35
        }
36
        if (substr($this->path, -5) === '.yaml' || substr($this->path, -4) === '.yml') {
37
            $jsonData = Yaml::parse($fileData, Yaml::PARSE_OBJECT);
38
        } else {
39
            $jsonData = json_decode($fileData);
40
        }
41
42
        if ($this->toYaml) {
43
            $result = Yaml::dump($jsonData, 2, 2, Yaml::DUMP_OBJECT_AS_MAP);
44
        } else {
45
            $result = json_encode($jsonData, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES);
46
        }
47
48
        if ($this->output) {
49
            file_put_contents($this->output, $result);
50
        } else {
51
            echo $result;
52
        }
53
    }
54
55
}