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
|
|
|
} |