-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseStringClass.php
85 lines (69 loc) · 2.23 KB
/
ParseStringClass.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
Class ParseString
{
/**
* Массив полученных строк
*/
public $strings = [];
/**
* Исходная строка
*/
public $string = "";
/**
* Массив плейсхолдеров и замен
*/
public $parsed = [];
public function __construct(String $string)
{
$this->string = $string;
}
/**
* Получение списка сгенерированных строк
*/
public function getStrings()
{
$i = 0;
while(preg_match_all('/(\<([^<>]|<?R>)*\>)/', $this->string, $matches)) {
foreach($matches[0] as $match) {
$i++;
$level = "#{$i}";
array_push($this->parsed, [
'level' => $level,
'string' => $match,
'variations' => explode("::", str_replace(['<', '>'], '', $match))
]);
$this->string = str_replace($match, $level, $this->string);
}
}
$this->generateVariations($this->string);
if(strpos($this->string, '<') || strpos($this->string, '>') || strpos($this->string, '::')) {
throw new Exception("String syntax error");
return;
}
return $this->strings;
}
/**
* Получение одной строки из шаблона
*/
private function generateVariations(String $string)
{
if(preg_match_all('/(#(\d)*)/', $string, $results)) {
foreach($results[0] as $match) {
$variations = [];
array_walk( $this->parsed, function($value, $key) use ($match, &$variations) {
if($value['level'] === $match) {
$variations = $value['variations'];
return;
}
}, $counter);
foreach($variations as $variation) {
$templated_string = str_replace($match, $variation, $string);
$this->generateVariations($templated_string);
}
return;
}
}
array_push($this->strings, $string);
return;
}
}