Completed
Push — master ( b52eb8...f7dddb )
by Josh
04:05
created

OptimizeChooseDeadBranches::optimizeChoose()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 10
c 1
b 0
f 1
dl 0
loc 19
ccs 11
cts 11
cp 1
rs 9.2222
cc 6
nc 4
nop 0
crap 6
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2019 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 OptimizeChooseDeadBranches extends AbstractChooseOptimization
13
{
14
	/**
15
	* Test whether given XPath expression is always false
16
	*
17
	* @param  string $expr
18
	* @return bool
19
	*/
20 8
	protected function isAlwaysFalse($expr)
21
	{
22
		// Always false: empty strings, 0, or false()
23 8
		$regexp = '(^(?:""|\'\'|0|0*\\.0+|false\\s*\\(\\s*\\))$)';
24
25 8
		return (bool) preg_match($regexp, trim($expr));
26
	}
27
28
	/**
29
	* Test whether given XPath expression is always true
30
	*
31
	* @param  string $expr
32
	* @return bool
33
	*/
34 8
	protected function isAlwaysTrue($expr)
35
	{
36
		// Always true: non-empty strings, non-0 numbers, or true()
37 8
		$regexp = '(^(?:"[^"]++"|\'[^\']++\'|0[0-9]+|[1-9][0-9]*|[0-9]*\\.0*[1-9][0-9]*|true\\s*\\(\\s*\\))$)';
38
39 8
		return (bool) preg_match($regexp, trim($expr));
40
	}
41
42
	/**
43
	* Convert given xsl:when element into an xsl:otherwise element
44
	*
45
	* @param  DOMElement $when
46
	* @return void
47
	*/
48 5
	protected function makeOtherwise(DOMElement $when)
49
	{
50 5
		$otherwise = $this->createElement('xsl:otherwise');
51 5
		while ($when->firstChild)
52
		{
53 5
			$otherwise->appendChild($when->firstChild);
54
		}
55
56 5
		$when->parentNode->replaceChild($otherwise, $when);
57
	}
58
59
	/**
60
	* {@inheritdoc}
61
	*/
62 8
	protected function optimizeChoose()
63
	{
64 8
		$removeAll = false;
65 8
		$tests     = [];
66 8
		foreach ($this->getBranches() as $branch)
67
		{
68 8
			$test = trim($branch->getAttribute('test'));
69
70 8
			if ($removeAll || isset($tests[$test]) || $this->isAlwaysFalse($test))
71
			{
72 8
				$branch->parentNode->removeChild($branch);
73
			}
74 8
			elseif ($this->isAlwaysTrue($test))
75
			{
76 5
				$removeAll = true;
77 5
				$this->makeOtherwise($branch);
78
			}
79
80 8
			$tests[$test] = 1;
81
		}
82
	}
83
}