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\NodeTraits; |
9
|
|
|
|
10
|
|
|
use DOMElement; |
11
|
|
|
use DOMException; |
12
|
|
|
use DOMNode; |
13
|
|
|
use const DOM_SYNTAX_ERR; |
14
|
|
|
use function preg_match, strtolower; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @method mixed magicMethodsCall(string $name, array $arguments) |
18
|
|
|
*/ |
19
|
|
|
trait PolyfillMethods |
20
|
|
|
{ |
21
|
|
|
use MagicMethods |
22
|
|
|
{ |
23
|
|
|
MagicMethods::__call as magicMethodsCall; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function __call(string $name, array $arguments) |
27
|
|
|
{ |
28
|
|
|
if (preg_match('(^(insertAdjacent(?:Element|Text)|replaceChildren)$)i', $name)) |
29
|
|
|
{ |
30
|
|
|
$methodName = '_' . $name; |
31
|
|
|
|
32
|
|
|
return $this->$methodName(...$arguments); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return $this->magicMethodsCall($name, $arguments); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Insert given node relative to this element's position |
40
|
|
|
* |
41
|
|
|
* @param string $where One of 'beforebegin', 'afterbegin', 'beforeend', 'afterend' |
42
|
|
|
* @param DOMNode $node |
43
|
|
|
* @return void |
44
|
|
|
*/ |
45
|
|
|
protected function insertAdjacentNode(string $where, DOMNode $node): void |
46
|
|
|
{ |
47
|
|
|
match (strtolower($where)) |
48
|
|
|
{ |
49
|
|
|
'beforebegin' => $this->parentNode?->insertBefore($node, $this), |
50
|
|
|
'beforeend' => $this->appendChild($node), |
51
|
|
|
'afterend' => $this->parentNode?->insertBefore($node, $this->nextSibling), |
52
|
|
|
'afterbegin' => $this->insertBefore($node, $this->firstChild), |
53
|
|
|
default => throw new DOMException("'$where' is not one of 'beforebegin', 'afterbegin', 'beforeend', or 'afterend'", DOM_SYNTAX_ERR) |
54
|
|
|
}; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function _insertAdjacentElement(string $where, DOMElement $element): DOMElement |
58
|
|
|
{ |
59
|
|
|
$this->insertAdjacentNode($where, $element); |
60
|
|
|
|
61
|
|
|
return $element; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function _insertAdjacentText(string $where, string $text): void |
65
|
|
|
{ |
66
|
|
|
$node = $this->ownerDocument->createTextNode($text); |
67
|
|
|
$this->insertAdjacentNode($where, $node); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
private function _replaceChildren(...$nodes): void |
71
|
|
|
{ |
72
|
|
|
while (isset($this->lastChild)) |
73
|
|
|
{ |
74
|
|
|
$this->lastChild->remove(); |
75
|
|
|
} |
76
|
|
|
$this->append(...$nodes); |
|
|
|
|
77
|
|
|
} |
78
|
|
|
} |