AddEvent::addEvent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 17
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace HotRodCli\Jobs\Xml;
4
5
use Symfony\Component\Filesystem\Filesystem;
6
7
class AddEvent
8
{
9
    protected $filesystem;
10
11
    public function __construct(Filesystem $filesystem)
12
    {
13
        $this->filesystem = $filesystem;
14
    }
15
16
    public function handle(string $xmlFile, array $addition)
17
    {
18
        if (!$this->filesystem->exists($xmlFile)) {
19
            throw new \Exception('no such file');
20
        }
21
22
        try {
23
            $this->addEvent($xmlFile, $addition);
24
        } catch (\Throwable $e) {
25
            throw new \Exception($e->getMessage());
26
        }
27
    }
28
29
    protected function addEvent(string $xmlFile, array $addition)
30
    {
31
        $content = file_get_contents($xmlFile);
32
        $xmlArray = new \SimpleXMLElement($content);
33
34
        $newRoute = $xmlArray->addChild('event');
35
        $newRoute->addAttribute('name', $addition['event-name']);
36
        $observer = $newRoute->addChild('observer');
37
        $observer->addAttribute('name', $addition['observer-name']);
38
        $observer->addAttribute('instance', $addition['instance']);
39
40
        $dom = new \DOMDocument("1.0");
41
        $dom->preserveWhiteSpace = false;
42
        $dom->formatOutput = true;
43
        $dom->loadXML($xmlArray->asXML());
44
        $xmlArray = new \SimpleXMLElement($dom->saveXML());
45
        $xmlArray->asXML($xmlFile);
46
    }
47
}
48