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
|
|
|
|