1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Inspirum\XML\Builder; |
6
|
|
|
|
7
|
|
|
use DOMDocument; |
8
|
|
|
use DOMException; |
9
|
|
|
use Inspirum\XML\Exception\Handler; |
10
|
|
|
use RuntimeException; |
11
|
|
|
use function error_get_last; |
12
|
|
|
use function file_get_contents; |
13
|
|
|
use function sprintf; |
14
|
|
|
|
15
|
|
|
final class DefaultDocumentFactory implements DocumentFactory |
16
|
|
|
{ |
17
|
55 |
|
public function __construct( |
18
|
|
|
private readonly DOMDocumentFactory $factory, |
19
|
|
|
) { |
20
|
55 |
|
} |
21
|
|
|
|
22
|
43 |
|
public function create(?string $version = null, ?string $encoding = null): Document |
23
|
|
|
{ |
24
|
43 |
|
return new DefaultDocument($this->factory->create($version, $encoding)); |
25
|
|
|
} |
26
|
|
|
|
27
|
6 |
|
public function createForFile(string $filepath, ?string $version = null, ?string $encoding = null): Document |
28
|
|
|
{ |
29
|
6 |
|
$content = @file_get_contents($filepath); |
30
|
6 |
|
if ($content === false) { |
31
|
1 |
|
throw new RuntimeException(error_get_last()['message'] ?? sprintf('Failed to open file [%s]', $filepath)); |
32
|
|
|
} |
33
|
|
|
|
34
|
5 |
|
return $this->createForContent($content); |
35
|
|
|
} |
36
|
|
|
|
37
|
11 |
|
public function createForContent(string $content, ?string $version = null, ?string $encoding = null): Document |
38
|
|
|
{ |
39
|
11 |
|
$document = $this->factory->create($version, $encoding); |
40
|
11 |
|
$this->loadXML($document, $content); |
41
|
|
|
|
42
|
8 |
|
return new DefaultDocument($document); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @throws \DOMException |
47
|
|
|
*/ |
48
|
11 |
|
private function loadXML(DOMDocument $document, string $content): void |
49
|
|
|
{ |
50
|
11 |
|
Handler::withErrorHandlerForDOMDocument(static function () use ($document, $content): void { |
51
|
11 |
|
$document->preserveWhiteSpace = false; |
52
|
|
|
|
53
|
11 |
|
$loaded = $document->loadXML($content); |
54
|
9 |
|
if ($loaded === false) { |
55
|
1 |
|
throw new DOMException('\DOMDocument::loadXML() method failed'); |
56
|
|
|
} |
57
|
11 |
|
}); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|