|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @package s9e\RegexpBuilder |
|
5
|
|
|
* @copyright Copyright (c) 2016 The s9e Authors |
|
6
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php The MIT License |
|
7
|
|
|
*/ |
|
8
|
|
|
namespace s9e\RegexpBuilder\Passes; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Replaces (?:aax|bbx) with (?:aa|bb)x |
|
12
|
|
|
*/ |
|
13
|
|
|
class MergeSuffix extends AbstractPass |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* {@inheritdoc} |
|
17
|
|
|
*/ |
|
18
|
8 |
|
protected function canRun(array $strings) |
|
19
|
|
|
{ |
|
20
|
8 |
|
return (count($strings) > 1 && $this->hasMatchingSuffix($strings)); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* {@inheritdoc} |
|
25
|
|
|
*/ |
|
26
|
5 |
|
protected function runPass(array $strings) |
|
27
|
|
|
{ |
|
28
|
5 |
|
$newString = []; |
|
29
|
5 |
|
while ($this->hasMatchingSuffix($strings)) |
|
30
|
|
|
{ |
|
31
|
5 |
|
array_unshift($newString, end($strings[0])); |
|
32
|
5 |
|
$strings = $this->pop($strings); |
|
33
|
|
|
} |
|
34
|
5 |
|
array_unshift($newString, $strings); |
|
35
|
|
|
|
|
36
|
5 |
|
return [$newString]; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Test whether all given strings have the same last element |
|
41
|
|
|
* |
|
42
|
|
|
* @param array[] $strings |
|
43
|
|
|
* @return bool |
|
44
|
|
|
*/ |
|
45
|
7 |
|
protected function hasMatchingSuffix(array $strings) |
|
46
|
|
|
{ |
|
47
|
7 |
|
$suffix = end($strings[1]); |
|
48
|
7 |
|
foreach ($strings as $string) |
|
49
|
|
|
{ |
|
50
|
7 |
|
if (end($string) !== $suffix) |
|
51
|
|
|
{ |
|
52
|
7 |
|
return false; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
5 |
|
return ($suffix !== false); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Remove the last element of every string |
|
61
|
|
|
* |
|
62
|
|
|
* @param array[] $strings Original strings |
|
63
|
|
|
* @return array[] Processed strings |
|
64
|
|
|
*/ |
|
65
|
5 |
|
protected function pop(array $strings) |
|
66
|
|
|
{ |
|
67
|
5 |
|
$cnt = count($strings); |
|
68
|
5 |
|
$i = $cnt; |
|
69
|
5 |
|
while (--$i >= 0) |
|
70
|
|
|
{ |
|
71
|
5 |
|
array_pop($strings[$i]); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
// Remove empty elements then prepend one back at the start of the array if applicable |
|
75
|
5 |
|
$strings = array_filter($strings); |
|
76
|
5 |
|
if (count($strings) < $cnt) |
|
77
|
|
|
{ |
|
78
|
1 |
|
array_unshift($strings, []); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
5 |
|
return $strings; |
|
82
|
|
|
} |
|
83
|
|
|
} |