1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @package s9e\SweetDOM |
5
|
|
|
* @copyright Copyright (c) The s9e authors |
6
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php The MIT License |
7
|
|
|
*/ |
8
|
|
|
namespace s9e\SweetDOM; |
9
|
|
|
|
10
|
|
|
use DOMDocument; |
11
|
|
|
use DOMDocumentFragment; |
12
|
|
|
use DOMNode; |
13
|
|
|
use DOMNodeList; |
14
|
|
|
use DOMXPath; |
15
|
|
|
use function func_get_args; |
16
|
|
|
|
17
|
|
|
class Document extends DOMDocument |
18
|
|
|
{ |
19
|
|
|
public NodeCreator $nodeCreator; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @link https://www.php.net/manual/domdocument.construct.php |
23
|
26 |
|
*/ |
24
|
|
|
public function __construct(string $version = '1.0', string $encoding = '') |
25
|
26 |
|
{ |
26
|
|
|
parent::__construct($version, $encoding); |
27
|
26 |
|
|
28
|
|
|
$this->nodeCreator = new NodeCreator($this); |
29
|
|
|
|
30
|
|
|
$this->registerNodeClass('DOMAttr', Attr::class); |
31
|
|
|
$this->registerNodeClass('DOMCdataSection', CdataSection::class); |
32
|
|
|
$this->registerNodeClass('DOMComment', Comment::class); |
33
|
|
|
$this->registerNodeClass('DOMDocumentFragment', DocumentFragment::class); |
34
|
|
|
$this->registerNodeClass('DOMElement', Element::class); |
35
|
|
|
$this->registerNodeClass('DOMText', Text::class); |
36
|
2 |
|
} |
37
|
|
|
|
38
|
2 |
|
/** |
39
|
2 |
|
* Evaluate and return the result of a given XPath expression |
40
|
|
|
*/ |
41
|
1 |
|
public function evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed |
42
|
|
|
{ |
43
|
|
|
return $this->xpath('evaluate', func_get_args()); |
44
|
2 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Evaluate and return the first element of a given XPath query |
48
|
|
|
*/ |
49
|
|
|
public function firstOf(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): ?DOMNode |
50
|
|
|
{ |
51
|
|
|
return $this->xpath('query', func_get_args())->item(0); |
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
/** |
55
|
|
|
* Evaluate and return the result of a given XPath query |
56
|
2 |
|
*/ |
57
|
2 |
|
public function query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): DOMNodeList |
58
|
|
|
{ |
59
|
2 |
|
return $this->xpath('query', func_get_args()); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Execute a DOMXPath method and return the result |
64
|
|
|
*/ |
65
|
|
|
protected function xpath(string $methodName, array $args): mixed |
66
|
|
|
{ |
67
|
1 |
|
$xpath = new DOMXPath($this); |
68
|
|
|
$xpath->registerNamespace('xsl', 'http://www.w3.org/1999/XSL/Transform'); |
69
|
1 |
|
$xpath->registerNodeNamespaces = true; |
|
|
|
|
70
|
|
|
|
71
|
|
|
return $xpath->$methodName(...$args); |
72
|
|
|
} |
73
|
|
|
} |