Completed
Push — master ( ffa824...36bc47 )
by Dmitrij
01:42
created

AddPreference::addPreference()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 2
1
<?php
2
3
namespace HotRodCli\Jobs\Xml;
4
5
use Symfony\Component\Filesystem\Filesystem;
6
7
class AddPreference
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->addPreference($xmlFile, $addition);
24
        } catch (\Throwable $e) {
25
            throw new \Exception($e->getMessage());
26
        }
27
    }
28
29
    protected function addPreference(string $xmlFile, array $addition)
30
    {
31
        $content = file_get_contents($xmlFile);
32
        $xmlArray = new \SimpleXMLElement($content);
33
34
        $newRoute = $xmlArray->addChild('preference');
35
        $newRoute->addAttribute('for', $addition['for']);
36
        $newRoute->addAttribute('type', $addition['type']);
37
38
        $dom = new \DOMDocument("1.0");
39
        $dom->preserveWhiteSpace = false;
40
        $dom->formatOutput = true;
41
        $dom->loadXML($xmlArray->asXML());
42
        $xmlArray = new \SimpleXMLElement($dom->saveXML());
43
        $xmlArray->asXML($xmlFile);
44
    }
45
}
46