Completed
Branch TemplateNormalizations (46261a)
by Josh
14:15
created

InlineXPathLiterals::replaceElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 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
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
}