ParentNodePolyfill   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 13
c 1
b 0
f 0
dl 0
loc 40
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A insertAdjacentNode() 0 9 1
A replaceChildren() 0 7 2
A insertAdjacentElement() 0 5 1
A insertAdjacentText() 0 4 1
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 strtolower;
15
16
trait ParentNodePolyfill
17
{
18
	public function insertAdjacentElement(string $where, DOMElement $element): ?DOMElement
19
	{
20
		$this->insertAdjacentNode($where, $element);
21
22
		return $element;
23
	}
24
25
	public function insertAdjacentText(string $where, string $data): void
26
	{
27
		$node = $this->ownerDocument->createTextNode($data);
28
		$this->insertAdjacentNode($where, $node);
29
	}
30
31
	public function replaceChildren(...$nodes): void
32
	{
33
		while (isset($this->lastChild))
34
		{
35
			$this->lastChild->remove();
36
		}
37
		$this->append(...$nodes);
38
	}
39
40
	/**
41
	* Insert given node relative to this element's position
42
	*
43
	* @param  string  $where One of 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
44
	* @param  DOMNode $node
45
	* @return void
46
	*/
47
	private function insertAdjacentNode(string $where, DOMNode $node): void
48
	{
49
		match (strtolower($where))
50
		{
51
			'afterbegin'  => $this->prepend($node),
52
			'afterend'    => $this->after($node),
53
			'beforebegin' => $this->before($node),
54
			'beforeend'   => $this->appendChild($node),
55
			default       => throw new DOMException("'$where' is not one of 'beforebegin', 'afterbegin', 'beforeend', or 'afterend'", DOM_SYNTAX_ERR)
56
		};
57
	}
58
}