Completed
Push — master ( f3ce80...4602fe )
by Josh
22:18
created

containsUnsupportedExpression()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2016 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 DOMDocument;
11
use DOMXPath;
12
use s9e\TextFormatter\Configurator\Helpers\XPathHelper;
13
14
class FoldConstantXPathExpressions extends AbstractConstantFolding
15
{
16
	/**
17
	* @var DOMXPath
18
	*/
19
	protected $xpath;
20
21
	/**
22
	* Constructor
23
	*/
24
	public function __construct()
25
	{
26
		$this->xpath = new DOMXPath(new DOMDocument);
27
	}
28
29
	/**
30
	* {@inheritdoc}
31
	*/
32
	protected function getOptimizationPasses()
33
	{
34
		return [
35
			'(^(?:"[^"]*"|\'[^\']*\'|\\.[0-9]|[^"$&\'./:<=>@[\\]])++$)' => 'foldConstantXPathExpression'
36
		];
37
	}
38
39
	/**
40
	* Test whether given string contains an unsupported expression
41
	*
42
	* Will test for keywords, nodes and node functions as well as a few unsupported functions
43
	* such as format-number()
44
	*
45
	* @link https://www.w3.org/TR/xpath/#section-Node-Set-Functions
46
	* @link https://www.w3.org/TR/xslt#add-func
47
	*
48
	* @param  string $expr
49
	* @return bool
50
	*/
51
	protected function containsUnsupportedExpression($expr)
52
	{
53
		// Remove strings to avoid false-positives
54
		$expr = preg_replace('("[^"]*"|\'[^\']*\')', '', $expr);
55
56
		return (bool) preg_match('([a-z](?![a-z\\(])|(?:comment|text|processing-instruction|node|last|position|count|id|local-name|namespace-uri|name|document|key|format-number|current|unparsed-entity-uri|generate-id|system-property)\\()', $expr);
57
	}
58
59
	/**
60
	* Evaluate and replace a constant XPath expression
61
	*
62
	* @param  array  $m
63
	* @return string
64
	*/
65
	protected function foldConstantXPathExpression(array $m)
66
	{
67
		$expr = $m[0];
68
		if (!$this->containsUnsupportedExpression($expr))
69
		{
70
			$foldedExpr = XPathHelper::export($this->xpath->evaluate($expr));
71
			if (strlen($foldedExpr) < strlen($expr))
72
			{
73
				$expr = $foldedExpr;
74
			}
75
		}
76
77
		return $expr;
78
	}
79
}