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
|
|
|
class CoalesceSingleCharacterPrefix extends AbstractPass |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* {@inheritdoc} |
14
|
|
|
*/ |
15
|
5 |
|
protected function processStrings(array $strings) |
16
|
|
|
{ |
17
|
5 |
|
$newStrings = []; |
18
|
5 |
|
foreach ($this->getEligibleKeys($strings) as $keys) |
19
|
|
|
{ |
20
|
|
|
// Create a new string to hold the merged strings and replace the first element with |
21
|
|
|
// an empty character class |
22
|
2 |
|
$newString = $strings[$keys[0]]; |
23
|
2 |
|
$newString[0] = []; |
24
|
2 |
|
foreach ($keys as $key) |
25
|
|
|
{ |
26
|
2 |
|
$newString[0][] = [$strings[$key][0]]; |
27
|
2 |
|
unset($strings[$key]); |
28
|
|
|
} |
29
|
2 |
|
$newStrings[] = $newString; |
30
|
|
|
} |
31
|
|
|
|
32
|
5 |
|
return array_merge($newStrings, $strings); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Filter the list of eligible keys and keep those that have at least two matches |
37
|
|
|
* |
38
|
|
|
* @param array[] $eligibleKeys List of lists of keys |
39
|
|
|
* @return array[] |
40
|
|
|
*/ |
41
|
5 |
|
protected function filterEligibleKeys(array $eligibleKeys) |
42
|
|
|
{ |
43
|
5 |
|
$filteredKeys = []; |
44
|
5 |
|
foreach ($eligibleKeys as $k => $keys) |
45
|
|
|
{ |
46
|
4 |
|
if (count($keys) > 1) |
47
|
|
|
{ |
48
|
4 |
|
$filteredKeys[] = $keys; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
5 |
|
return $filteredKeys; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Get a list of keys of strings eligible to be merged together, grouped by suffix |
57
|
|
|
* |
58
|
|
|
* @param array[] $strings |
59
|
|
|
* @return array[] |
60
|
|
|
*/ |
61
|
5 |
|
protected function getEligibleKeys(array $strings) |
62
|
|
|
{ |
63
|
5 |
|
$eligibleKeys = []; |
64
|
5 |
|
foreach ($strings as $k => $string) |
65
|
|
|
{ |
66
|
5 |
|
if (!is_array($string[0]) && isset($string[1])) |
67
|
|
|
{ |
68
|
4 |
|
$suffix = serialize(array_slice($string, 1)); |
69
|
5 |
|
$eligibleKeys[$suffix][] = $k; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
5 |
|
return $this->filterEligibleKeys($eligibleKeys); |
74
|
|
|
} |
75
|
|
|
} |