XMLExport::export()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 37
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 21.748

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 24
c 2
b 0
f 0
nc 5
nop 3
dl 0
loc 37
ccs 3
cts 24
cp 0.125
crap 21.748
rs 9.2248
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Wowstack\Dbc\Export;
6
7
use Doctrine\Common\Inflector\Inflector;
8
use Wowstack\Dbc\DBC;
9
use Wowstack\Dbc\DBCException;
10
11
/**
12
 * Implements conversion of DBC files and their records into XML files.
13
 */
14
class XMLExport implements ExportInterface
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19 2
    public function export(DBC $dbc, string $targetPath = 'php://output', string $version = '1.12.1')
20
    {
21 2
        if (null === $dbc->getMap()) {
22 2
            throw new DBCException('DBC export requires a map.');
23
        }
24
25
        $dom = new \DOMDocument('1.0', 'utf-8');
26
        $dom->formatOutput = true;
27
28
        $dbcRoot = $dom->appendChild($dom->createElement('dbc'));
29
30
        $dbcRootName = $dom->createAttribute('name');
31
        $dbcRootName->value = Inflector::pluralize($dbc->getName());
32
        $dbcRoot->appendChild($dbcRootName);
33
34
        $dbcRootVersion = $dom->createAttribute('version');
35
        $dbcRootVersion->value = $version;
36
        $dbcRoot->appendChild($dbcRootVersion);
37
38
        $erecords = $dbcRoot->appendChild($dom->createElement(Inflector::pluralize($dbc->getName())));
39
40
        foreach ($dbc as $index => $record) {
41
            $pairs = $record->read();
42
            $erecord = $erecords->appendChild($dom->createElement(Inflector::singularize($dbc->getName())));
43
            foreach ($pairs as $field => $value) {
44
                $attr = $dom->createAttribute($field);
45
                if (is_string($value)) {
46
                    $attr->value = htmlspecialchars($value, ENT_XML1, 'UTF-8');
47
                } else {
48
                    $attr->value = $value;
49
                }
50
                $erecord->appendChild($attr);
51
            }
52
        }
53
54
        $data = $dom->saveXML();
55
        file_put_contents($targetPath, $data);
56
    }
57
}
58