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); |
|
|
|
|
32
|
|
|
} |
33
|
5 |
|
$fileData = file_get_contents($path); |
34
|
5 |
|
if (!$fileData) { |
35
|
|
|
$this->response->error('Unable to read ' . $path); |
36
|
|
|
die(1); |
|
|
|
|
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
|
|
|
} |
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.