UpdateKeyCommand.php
2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Grasmash\YamlCli\Command;
use Dflydev\DotAccessData\Data;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class CreateProjectCommand
*
* @package Grasmash\YamlCli\Command
*/
class UpdateKeyCommand extends CommandBase
{
/**
* {inheritdoc}
*/
protected function configure()
{
$this
->setName('update:key')
->setDescription('Update a specific key in a YAML file.')
->addUsage("path/to/file.yml example.key example.new-key")
->addArgument(
'filename',
InputArgument::REQUIRED,
"The filename of the YAML file"
)
->addArgument(
'key',
InputArgument::REQUIRED,
"The original key, in dot notation"
)
->addArgument(
'new-key',
InputArgument::REQUIRED,
"The new key, in dot notation"
);
}
/**
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return int 0 if everything went fine, or an exit code
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$filename = $input->getArgument('filename');
$key = $input->getArgument('key');
$new_key = $input->getArgument('new-key');
$yaml_parsed = $this->loadYamlFile($filename);
if (!$yaml_parsed) {
// Exit with a status of 1.
return 1;
}
$data = new Data($yaml_parsed);
if (!$this->checkKeyExists($data, $key)) {
$this->output->writeln("<error>The key '$key' does not exist in $filename.</error>");
return 1;
}
$value = $data->get($key);
$data->set($new_key, $value);
$data->remove($key);
if ($this->writeYamlFile($filename, $data)) {
$this->output->writeln("<info>The key '$key' was changed to '$new_key' in $filename.</info>");
return 0;
}
return 1;
}
}