1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace dlindberg\DOMDocumentFactory; |
6
|
|
|
|
7
|
|
|
class DOMDocumentFactory |
8
|
|
|
{ |
9
|
|
|
private $config; |
10
|
|
|
|
11
|
27 |
|
public function __construct(DOMDocumentFactoryConfig $config = null) |
12
|
|
|
{ |
13
|
27 |
|
$this->config = $config ?? new DOMDocumentFactoryConfig(); |
14
|
27 |
|
} |
15
|
|
|
|
16
|
3 |
|
public function __invoke(string $blob): \DOMNode |
17
|
|
|
{ |
18
|
3 |
|
return $this->getNode($blob); |
19
|
|
|
} |
20
|
|
|
|
21
|
24 |
|
public function getDocument(string $blob): \DOMDocument |
22
|
|
|
{ |
23
|
24 |
|
$doc = new \DOMDocument($this->config->version, $this->config->encoding); |
24
|
24 |
|
$doc->recover = $this->config->recover; |
25
|
24 |
|
$doc->formatOutput = $this->config->formatOutput; |
26
|
24 |
|
$doc->preserveWhiteSpace = $this->config->preserveWhiteSpace; |
27
|
24 |
|
$doc->loadHTML($this->config->loadString($blob), $this->config->DOMOptions); |
28
|
|
|
|
29
|
24 |
|
return $doc; |
30
|
|
|
} |
31
|
|
|
|
32
|
9 |
|
public static function getDomNode(string $blob, DOMDocumentFactoryConfig $config = null): \DOMNode |
33
|
|
|
{ |
34
|
9 |
|
return (new DOMDocumentFactory($config))->getNode($blob); |
35
|
|
|
} |
36
|
|
|
|
37
|
3 |
|
public static function stringifyNode(\DOMNode $node, DOMDocumentFactoryConfig $config = null): string |
38
|
|
|
{ |
39
|
3 |
|
return (new DOMDocumentFactory($config))->stringify($node); |
40
|
|
|
} |
41
|
|
|
|
42
|
3 |
|
public static function stringifyNodeList(\DOMNodeList $nodes, DOMDocumentFactoryConfig $config = null): array |
43
|
|
|
{ |
44
|
3 |
|
return (new DOMDocumentFactory($config))->stringifyFromList($nodes); |
45
|
|
|
} |
46
|
|
|
|
47
|
21 |
|
public function getNode(string $blob): \DOMNode |
48
|
|
|
{ |
49
|
21 |
|
return $this->getDocument($blob)->getElementsByTagName('body')->item(0); |
50
|
|
|
} |
51
|
|
|
|
52
|
12 |
|
public function stringify(\DOMNode $input): string |
53
|
|
|
{ |
54
|
12 |
|
return $this->config->outputString($input->ownerDocument->saveXML($input)); |
55
|
|
|
} |
56
|
|
|
|
57
|
6 |
|
public function stringifyFromList(\DOMNodeList $input): array |
58
|
|
|
{ |
59
|
6 |
|
return $this->stringifyWalkSiblings($input->item(0)); |
60
|
|
|
} |
61
|
|
|
|
62
|
6 |
|
private function stringifyWalkSiblings(\DOMNode $node, array $carry = []): array |
63
|
|
|
{ |
64
|
6 |
|
$carry[] = $this->stringify($node); |
65
|
|
|
|
66
|
6 |
|
return null === $node->nextSibling ? $carry : $this->stringifyWalkSiblings($node->nextSibling, $carry); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|