-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDOMDocumentFactory.php
99 lines (79 loc) · 2.53 KB
/
DOMDocumentFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMDocument;
use RuntimeException;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XML\Exception\IOException;
use SimpleSAML\XML\Exception\UnparseableXMLException;
use function defined;
use function file_get_contents;
use function libxml_clear_errors;
use function libxml_get_last_error;
use function libxml_use_internal_errors;
use function sprintf;
/**
* @package simplesamlphp/xml-common
*/
final class DOMDocumentFactory
{
/**
* @param string $xml
* @param non-empty-string $xml
*
* @return \DOMDocument
*/
public static function fromString(string $xml): DOMDocument
{
Assert::notWhitespaceOnly($xml);
$internalErrors = libxml_use_internal_errors(true);
libxml_clear_errors();
$domDocument = self::create();
$options = LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NONET | LIBXML_PARSEHUGE | LIBXML_NSCLEAN;
if (defined('LIBXML_COMPACT')) {
$options |= LIBXML_COMPACT;
}
$loaded = $domDocument->loadXML($xml, $options);
libxml_use_internal_errors($internalErrors);
if (!$loaded) {
$error = libxml_get_last_error();
libxml_clear_errors();
throw new UnparseableXMLException($error);
}
libxml_clear_errors();
foreach ($domDocument->childNodes as $child) {
if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
throw new RuntimeException(
'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body',
);
}
}
return $domDocument;
}
/**
* @param string $file
*
* @return \DOMDocument
*/
public static function fromFile(string $file): DOMDocument
{
error_clear_last();
$xml = @file_get_contents($file);
if ($xml === false) {
$e = error_get_last();
$error = $e['message'] ?? "Check that the file exists and can be read.";
throw new IOException("File '$file' was not loaded; $error");
}
Assert::notWhitespaceOnly($xml, sprintf('File "%s" does not have content', $file), RuntimeException::class);
return static::fromString($xml);
}
/**
* @param string $version
* @param string $encoding
* @return \DOMDocument
*/
public static function create(string $version = '1.0', string $encoding = 'UTF-8'): DOMDocument
{
return new DOMDocument($version, $encoding);
}
}