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\RendererGenerators\PHP\XPathConvertor\Convertors; |
9
|
|
|
|
10
|
|
|
class MultiByteStringManipulation extends AbstractConvertor |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* {@inheritdoc} |
14
|
|
|
*/ |
15
|
80 |
|
public function getMatchers(): array |
16
|
|
|
{ |
17
|
|
|
return [ |
18
|
80 |
|
'String:Substring' => 'substring \\( ((?&String)) , ((?&Attribute)|(?&Math)|(?&Number)) (?:, ((?&Attribute)|(?&Math)|(?&Number)))? \\)' |
19
|
|
|
]; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Convert a substring() function call |
24
|
|
|
* |
25
|
|
|
* @param string $exprString |
26
|
|
|
* @param string $exprPos |
27
|
|
|
* @param string $exprLen |
28
|
|
|
* @return string |
29
|
|
|
*/ |
30
|
10 |
|
public function parseSubstring($exprString, $exprPos, $exprLen = null) |
31
|
|
|
{ |
32
|
|
|
// Try to fix negative lengths when possible |
33
|
10 |
|
if (is_numeric($exprPos) && is_numeric($exprLen) && $exprPos < 1) |
34
|
|
|
{ |
35
|
2 |
|
$exprLen += $exprPos - 1; |
36
|
|
|
} |
37
|
|
|
|
38
|
10 |
|
$args = []; |
39
|
10 |
|
$args[] = $this->recurse($exprString); |
40
|
10 |
|
$args[] = $this->convertPos($exprPos); |
41
|
10 |
|
$args[] = (isset($exprLen)) ? $this->convertLen($exprLen) : 'null'; |
42
|
10 |
|
$args[] = "'utf-8'"; |
43
|
|
|
|
44
|
10 |
|
return 'mb_substr(' . implode(',', $args) . ')'; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Convert the length expression of a substring() call |
49
|
|
|
* |
50
|
|
|
* @param string $expr |
51
|
|
|
* @return string |
52
|
|
|
*/ |
53
|
7 |
|
protected function convertLen($expr) |
54
|
|
|
{ |
55
|
|
|
// NOTE: negative values for the second argument do not produce the same result as |
56
|
|
|
// specified in XPath if the argument is not a literal number |
57
|
7 |
|
if (is_numeric($expr)) |
58
|
|
|
{ |
59
|
5 |
|
return (string) max(0, $expr); |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
return 'max(0,' . $this->recurse($expr) . ')'; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Convert the position expression of a substring() call |
67
|
|
|
* |
68
|
|
|
* @param string $expr |
69
|
|
|
* @return string |
70
|
|
|
*/ |
71
|
10 |
|
protected function convertPos($expr) |
72
|
|
|
{ |
73
|
10 |
|
if (is_numeric($expr)) |
74
|
|
|
{ |
75
|
8 |
|
return (string) max(0, $expr - 1); |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
return 'max(0,' . $this->recurse($expr) . '-1)'; |
79
|
|
|
} |
80
|
|
|
} |