1 | <?php |
||
22 | final class YamlConvertCommand extends BaseCommand |
||
23 | { |
||
24 | private $formats = [ |
||
25 | 'yaml' => 'yaml', |
||
26 | 'yml' => 'yaml', |
||
27 | 'json' => 'json', |
||
28 | ]; |
||
29 | |||
30 | 9 | protected function configure() |
|
31 | { |
||
32 | $this |
||
33 | 9 | ->setName('yaml-convert') |
|
34 | 9 | ->setDescription('Converts a composer.yaml to json or vice-versa') |
|
35 | 9 | ->addArgument('input', InputArgument::OPTIONAL, 'The input file') |
|
36 | 9 | ->addArgument('output', InputArgument::OPTIONAL, 'The output file') |
|
37 | ; |
||
38 | 9 | } |
|
39 | |||
40 | 8 | protected function execute(InputInterface $input, OutputInterface $output) |
|
41 | { |
||
42 | 8 | $files = $this->getFiles([ |
|
43 | 8 | 'input' => $input->getArgument('input'), |
|
44 | 8 | 'output' => $input->getArgument('output'), |
|
45 | ]); |
||
46 | |||
47 | 8 | $from = $this->getFormat($files['input'], 'input'); |
|
48 | |||
49 | 7 | if (!is_file($files['input'])) { |
|
50 | 2 | throw new \InvalidArgumentException(sprintf('The input file "%s" does not exist.', $files['input'])); |
|
51 | } |
||
52 | |||
53 | 5 | if (null === $files['output']) { |
|
54 | 1 | $files['output'] = 'json' === $from ? 'composer.yaml' : 'composer.json'; |
|
55 | } else { |
||
56 | 4 | $to = $this->getFormat($files['output'], 'output'); |
|
57 | |||
58 | 4 | if ($from === $to) { |
|
59 | 1 | throw new \InvalidArgumentException(sprintf('Input format "%s" is same as output format.', $from)); |
|
60 | } |
||
61 | } |
||
62 | |||
63 | 4 | $content = file_get_contents($files['input']); |
|
64 | |||
65 | 4 | if ('json' === $from) { |
|
66 | 2 | $converted = Yaml::dump(JsonFile::parseJson($content)); |
|
67 | } else { |
||
68 | 2 | $converted = JsonFile::encode(Yaml::parse($content))."\n"; |
|
69 | } |
||
70 | |||
71 | 4 | file_put_contents($files['output'], $converted); |
|
72 | 4 | $output->writeln(sprintf('Converted "%s" to "%s"', $files['input'], $files['output'])); |
|
73 | 4 | } |
|
74 | |||
75 | 8 | private function getFiles(array $data) |
|
91 | |||
92 | 8 | private function getFormat($file, $type) |
|
104 | } |
||
105 |