Passed
Push — master ( b97c32...e7e450 )
by Carlos C
10:36 queued 12s
created

OriginsIO::originsFromString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\SatCatalogosPopulate\Origins;
6
7
use DOMDocument;
8
use SimpleXMLElement;
9
10
class OriginsIO
11
{
12
    private OriginsTranslator $translator;
13
14 2
    public function __construct()
15
    {
16 2
        $this->translator = new OriginsTranslator();
17
    }
18
19 2
    public function readFile(string $filename): Origins
20
    {
21 2
        return $this->originsFromString(file_get_contents($filename) ?: '');
22
    }
23
24
    public function writeFile(string $filename, Origins $origins): void
25
    {
26
        file_put_contents($filename, $this->originsToString($origins));
27
    }
28
29 2
    public function originsFromString(string $xmlContent): Origins
30
    {
31 2
        $origins = [];
32
        /** @noinspection PhpUnhandledExceptionInspection */
33 2
        $xml = new SimpleXMLElement($xmlContent);
34 2
        foreach ($xml->{'origin'} as $origin) {
35 2
            $origins[] = $this->readOrigin($origin);
36
        }
37
38 2
        return new Origins($origins);
39
    }
40
41 2
    protected function readOrigin(SimpleXMLElement $origin): OriginInterface
42
    {
43 2
        $attributes = [];
44
        /** @var array<string, SimpleXMLElement> $sources */
45 2
        $sources = $origin->attributes() ?? [];
46 2
        foreach ($sources as $key => $value) {
47 2
            $attributes[$key] = (string) $value;
48
        }
49
50 2
        return $this->translator->originFromArray($attributes);
51
    }
52
53 1
    public function originsToString(Origins $origins): string
54
    {
55 1
        $document = new DOMDocument('1.0', 'UTF-8');
56 1
        $document->formatOutput = true;
57 1
        $document->preserveWhiteSpace = false;
58 1
        $root = $document->createElement('origins');
59 1
        $document->appendChild($root);
60
        /** @var OriginInterface $origin */
61 1
        foreach ($origins as $origin) {
62 1
            $child = $document->createElement('origin');
63 1
            foreach ($this->translator->originToArray($origin) as $key => $value) {
64 1
                $child->setAttribute($key, $value);
65
            }
66 1
            $root->appendChild($child);
67
        }
68
69 1
        return $document->saveXML() ?: '';
70
    }
71
}
72