Completed
Branch TemplateNormalizations (ae42e4)
by Josh
33:16
created

NormalizeElementNames::normalize()   C

Complexity

Conditions 7
Paths 20

Size

Total Lines 48
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 21
nc 20
nop 1
dl 0
loc 48
rs 6.7272
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A NormalizeElementNames::normalizeElement() 0 11 2
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2017 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Configurator\TemplateNormalizations;
9
10
use DOMAttr;
11
use DOMElement;
12
13
class NormalizeElementNames extends AbstractNormalization
14
{
15
	/**
16
	* {@inheritdoc}
17
	*/
18
	protected $queries = [
19
		'//*[namespace-uri() != $XSL]',
20
		'//xsl:element[not(contains(@name, "{"))]'
21
	];
22
23
	/**
24
	* {@inheritdoc}
25
	*/
26
	protected function normalizeElement(DOMElement $element)
27
	{
28
		if ($this->isXsl($element, 'element'))
29
		{
30
			$this->replaceXslElement($element);
31
		}
32
		else
33
		{
34
			$this->replaceElement($element);
35
		}
36
	}
37
38
	/**
39
	* Normalize and replace a non-XSL element if applicable
40
	*
41
	* @param  DOMElement $element
42
	* @return void
43
	*/
44
	protected function replaceElement(DOMElement $element)
45
	{
46
		$elName = $this->lowercase($element->localName);
47
		if ($elName === $element->localName)
48
		{
49
			return;
50
		}
51
52
		// Create a new element with the correct name
53
		$newElement = (is_null($element->namespaceURI))
54
		            ? $this->ownerDocument->createElement($elName)
55
		            : $this->ownerDocument->createElementNS($element->namespaceURI, $elName);
56
57
		// Move every child to the new element
58
		while ($element->firstChild)
59
		{
60
			$newElement->appendChild($element->removeChild($element->firstChild));
61
		}
62
63
		// Copy attributes to the new node
64
		foreach ($element->attributes as $attribute)
65
		{
66
			$newElement->setAttributeNS(
67
				$attribute->namespaceURI,
68
				$attribute->nodeName,
69
				$attribute->value
70
			);
71
		}
72
73
		// Replace the old element with the new one
74
		$element->parentNode->replaceChild($newElement, $element);
75
	}
76
77
	/**
78
	* Normalize the name used in a xsl:element
79
	*
80
	* @param  DOMElement $element
81
	* @return void
82
	*/
83
	protected function replaceXslElement(DOMElement $element)
84
	{
85
		$elName = $this->lowercase($element->getAttribute('name'));
86
		$element->setAttribute('name', $elName);
87
	}
88
}