Completed
Pull Request — master (#16)
by
unknown
02:43
created

NewServiceEventCommand::executeJsonEvent()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 37
rs 9.328
c 0
b 0
f 0
1
<?php
2
3
namespace TheAentMachine\AentDockerCompose\Command;
4
5
use Symfony\Component\Console\Question\ChoiceQuestion;
6
use Symfony\Component\Yaml\Yaml;
7
use TheAentMachine\AentDockerCompose\DockerCompose\DockerComposeService;
8
use TheAentMachine\AentDockerCompose\YamlTools\YamlTools;
9
use TheAentMachine\JsonEventCommand;
10
use TheAentMachine\Service\Service;
11
12
class NewServiceEventCommand extends JsonEventCommand
13
{
14
15
    protected function getEventName(): string
16
    {
17
        return 'NEW_SERVICE';
18
    }
19
20
    protected function executeJsonEvent(array $payload): ?array
21
    {
22
        $service = Service::parsePayload($payload);
23
        $formattedPayload = DockerComposeService::dockerComposeServiceSerialize($service);
24
25
        // $this->log->debug(json_encode($formattedPayload, JSON_PRETTY_PRINT));
26
27
        $yml = Yaml::dump($formattedPayload, 256, 4, Yaml::DUMP_OBJECT_AS_MAP);
28
        file_put_contents(YamlTools::TMP_YAML_FILE, $yml);
29
30
31
        $dockerComposeService = new DockerComposeService($this->log);
32
        $dockerComposeFilePathnames = $dockerComposeService->getDockerComposePathnames();
33
        if (count($dockerComposeFilePathnames) === 1) {
34
            $toMerge = $dockerComposeFilePathnames;
35
        } else {
36
            $helper = $this->getHelper('question');
37
            $question = new ChoiceQuestion(
38
                'Please choose the docker-compose file(s) in which the service will be added (e.g. 0,1) : ',
39
                $dockerComposeFilePathnames,
40
                null
41
            );
42
            $question->setMultiselect(true);
43
44
            $toMerge = $helper->ask($this->input, $this->output, $question);
45
        }
46
47
        foreach ($toMerge as $file) {
48
            YamlTools::merge($file, YamlTools::TMP_YAML_FILE, YamlTools::TMP_MERGED_FILE);
49
            DockerComposeService::checkDockerComposeFileValidity(YamlTools::TMP_MERGED_FILE);
50
            copy(YamlTools::TMP_MERGED_FILE, $file);
51
        }
52
53
        unlink(YamlTools::TMP_YAML_FILE);
54
        unlink(YamlTools::TMP_MERGED_FILE);
55
56
        return null;
57
    }
58
}
59