Completed
Push — master ( f7b88b...3755ed )
by Josh
14:40
created

NormalizeElementNames   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 76
rs 10
c 0
b 0
f 0

3 Methods

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