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

InlineXPathLiterals::normalize()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 36
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 17
nc 6
nop 1
dl 0
loc 36
rs 8.439
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A InlineXPathLiterals::getTextContent() 0 17 3
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
use s9e\TextFormatter\Configurator\Helpers\AVTHelper;
13
14
class InlineXPathLiterals extends AbstractNormalization
15
{
16
	/**
17
	* {@inheritdoc}
18
	*/
19
	protected $queries = [
20
		'//xsl:value-of',
21
		'//*[namespace-uri() != $XSL]/@*[contains(., "{")]'
22
	];
23
24
	/**
25
	* Return the textContent value of an XPath expression
26
	*
27
	* @param  string      $expr XPath expression
28
	* @return string|bool       Text value, or FALSE if not a literal
29
	*/
30
	protected function getTextContent($expr)
31
	{
32
		$expr = trim($expr);
33
34
		if (preg_match('(^(?:\'[^\']*\'|"[^"]*")$)', $expr))
35
		{
36
			return substr($expr, 1, -1);
37
		}
38
39
		if (preg_match('(^0*([0-9]+(?:\\.[0-9]+)?)$)', $expr, $m))
40
		{
41
			// NOTE: we specifically ignore leading zeros
42
			return $m[1];
43
		}
44
45
		return false;
46
	}
47
48
	/**
49
	* {@inheritdoc}
50
	*/
51
	protected function normalizeAttribute(DOMAttr $attribute)
52
	{
53
		AVTHelper::replace(
54
			$attribute,
55
			function ($token)
56
			{
57
				if ($token[0] === 'expression')
58
				{
59
					$textContent = $this->getTextContent($token[1]);
60
					if ($textContent !== false)
61
					{
62
						// Turn this token into a literal
63
						$token = ['literal', $textContent];
64
					}
65
				}
66
67
				return $token;
68
			}
69
		);
70
	}
71
72
	/**
73
	* {@inheritdoc}
74
	*/
75
	protected function normalizeElement(DOMElement $element)
76
	{
77
		$textContent = $this->getTextContent($element->getAttribute('select'));
78
		if ($textContent !== false)
79
		{
80
			$element->parentNode->replaceChild($this->createTextNode($textContent), $element);
81
		}
82
	}
83
84
	/**
85
	* Replace an xsl:value-of element with a text node
86
	*
87
	* @param  DOMElement $valueOf
88
	* @param  string     $textContent
89
	* @return void
90
	*/
91
	protected function replaceElement(DOMElement $valueOf, $textContent)
92
	{
93
	}
94
}