This repository has been archived by the owner on Jun 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
ParserPCRE.php
166 lines (120 loc) · 3.12 KB
/
ParserPCRE.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
<?php
const EXPRESSION = <<<'PCRE'
`
\G
(?<block_list>
(?|
# Block
## Block opening
<!--
[ \n\r\t]*
wp:(?<block_name>(?:[a-z][a-z0-9\-]*/)?[a-z][a-z0-9\-]*)
[ \n\r\t]+
(?<block_attributes>{[^}]+})?
[ \n\r\t]*
(?:
## Void
/-->
(*MARK:void_block)
|
## Balanced
-->
## Block children
(?<block_children>
(?&block_list)
)*
## Block closing
<!--[ \n\r\t]*/wp:\g{block_name}[ \n\r\t]*-->
(*MARK:balanced_block)
)
|
# Phrase
.+?(?=<!--[ \n\r\t]*/?wp:)
(*MARK:phrase)
|
# Phrase tail
.+
(*MARK:phrase_tail)
)
)
`xsm
PCRE;
/*
*/
const DATA = <<<'DATA'
first
<!-- wp:foo --><!-- wp:bar -->blabla<!-- /wp:bar --><!-- /wp:foo -->
<!-- wp:baz {"a": "b"} -->yolo<!-- /wp:baz -->
<!-- wp:q/ux {"x": "y"} /-->
haa
<!-- more -->
tail tail
DATA;
class Block
{
public $name;
public $attributes;
public $children;
}
class Phrase
{
public $content;
}
function parse(string $data)
{
$offset = 0;
$max_offset = strlen($data);
do {
$preg = preg_match(
EXPRESSION,
$data,
$matches,
0,
$offset
);
if (0 === $preg || empty($matches)) {
break;
}
switch ($matches['MARK']) {
case 'phrase':
case 'phrase_tail':
$phrase = new Phrase();
$phrase->content = $matches[1];
yield $phrase;
break;
case 'void_block':
$block = new Block();
$block->name = $matches['block_name'];
if (!empty($matches['block_attributes'])) {
$block->attributes = json_decode($matches['block_attributes']);
}
yield $block;
break;
case 'balanced_block':
$block = new Block();
$block->name = $matches['block_name'];
if (!empty($matches['block_attributes'])) {
$block->attributes = json_decode($matches['block_attributes']);
}
if (!empty($matches['block_children'])) {
$block->children = $matches['block_children'];
}
yield $block;
break;
}
$offset += strlen($matches[0]);
} while ($offset < $max_offset);
}
function unfold(string $data, int $depth = 0)
{
$output = [];
foreach (parse($data) as $node) {
if ($node instanceof Block && !empty($node->children)) {
$node->children = unfold($node->children);
}
$output[] = $node;
}
return $output;
}
echo '# ', str_replace("\n", "\n" . '# ', DATA), "\n\n";
echo json_encode(unfold(DATA), JSON_PRETTY_PRINT);