|
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
|
|
|
} |