XmlParser::parse()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpEpub;
6
7
use SimpleXMLElement;
8
9
class XmlParser
10
{
11
    /**
12
     * Loads an XML file and returns a SimpleXMLElement.
13
     *
14
     * @param string $filePath The path to the XML file.
15
     *
16
     * @throws Exception If the XML file cannot be loaded.
17
     */
18 46
    public function parse(string $filePath): SimpleXMLElement
19
    {
20 46
        if (! file_exists($filePath)) {
21 2
            throw new Exception("XML file not found: {$filePath}");
22
        }
23
24 44
        $xml = @simplexml_load_file($filePath);
25 44
        if ($xml === false) {
26 2
            throw new Exception("Failed to load XML file: {$filePath}");
27
        }
28
29 43
        return $xml;
30
    }
31
32
    /**
33
     * Saves a SimpleXMLElement to a file.
34
     *
35
     * @param SimpleXMLElement $xml The XML element to save.
36
     * @param string $filePath The path where the XML should be saved.
37
     *
38
     * @throws Exception If the XML file cannot be saved.
39
     */
40 2
    public function save(SimpleXMLElement $xml, string $filePath): void
41
    {
42 2
        $result = $xml->asXML($filePath);
43 2
        if ($result === false) {
44 1
            throw new Exception("Failed to save XML file: {$filePath}");
45
        }
46
    }
47
}
48