-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathFieldParser.php
465 lines (400 loc) · 12.9 KB
/
FieldParser.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php namespace Winter\Storm\Parse\Syntax;
use Winter\Storm\Exception\ApplicationException;
/**
* Dynamic Syntax parser
*/
class FieldParser
{
/**
* @var string Template contents
*/
protected $template = '';
/**
* @var array Extracted fields from the template
* The array key should match a unique field name, and the value
* is another array with values:
*
* - type: the tag name, eg: text
* - default: the default tag text
* - *: defined parameters
*/
protected $fields = [];
/**
* @var array Complete tag strings for each field. The array
* key will match the unique field name and the value is the
* complete tag string, eg: {text}...{/text}
*/
protected $tags = [];
/**
* @var string A prefix to place before all tag references
* eg: {namespace:text}{/namespace:text}
*/
protected $tagPrefix = '';
/**
* @var array Registered template tags
*/
protected $registeredTags = [
'text',
'textarea',
'richeditor',
'markdown',
'fileupload',
'mediafinder',
'dropdown',
'colorpicker',
'radio',
'checkbox',
'checkboxlist',
'datepicker',
'balloon-selector',
'repeater',
'variable'
];
/**
* Constructor.
*
* @param string $template Template to parse.
* @param array $options
*/
final public function __construct($template, $options = [])
{
$this->tagPrefix = array_get($options, 'tagPrefix', '');
$this->template = $template;
$this->processTemplate($template);
}
/**
* Processes repeating tags first, then registered tags and assigns
* the results to local object properties.
*
* @param string $template
* @return void
*/
protected function processTemplate($template)
{
// Process repeaters
list($template, $repeatTags, $repeatfields) = $this->processRepeaterTags($template);
// Process registered tags
list($tags, $fields) = $this->processTags($template);
$this->tags += $tags;
$this->fields += $fields;
/*
* Layer the repeater tags over the standard ones to retain
* the original sort order
*/
foreach ($repeatfields as $field => $params) {
$this->fields[$field] = $params;
}
foreach ($repeatTags as $field => $params) {
$this->tags[$field] = $params;
}
}
/**
* Static helper for new instances of this class.
* @param string $template
* @param array $options
* @return static
*/
public static function parse($template, $options = [])
{
return new static($template, $options);
}
/**
* Returns all tag strings found in the template
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* Returns tag strings for a specific field
* @param string $field
* @return array
*/
public function getFieldTags($field)
{
return $this->tags[$field] ?? [];
}
/**
* Returns all field definitions found in the template
* @return array
*/
public function getFields()
{
return $this->fields;
}
/**
* Returns defined parameters for a single field
* @param string $field
* @return array
*/
public function getFieldParams($field)
{
return $this->fields[$field] ?? [];
}
/**
* Returns default values for all fields.
* @param array $fields
* @return array
*/
public function getDefaultParams($fields = null)
{
if (is_null($fields)) {
$fields = $this->fields;
}
$defaults = [];
foreach ($fields as $field => $params) {
if (empty($params['type'])) {
continue;
}
if ($params['type'] == 'repeater') {
$defaults[$field] = [];
$defaults[$field][] = $this->getDefaultParams(array_get($params, 'fields', []));
} else {
$defaults[$field] = $params['default'] ?? null;
}
}
return $defaults;
}
/**
* Processes all repeating tags against a template, this will strip
* any repeaters from the template for further processing.
* @param string $template
* @return array
*/
protected function processRepeaterTags($template)
{
list($tags, $fields) = $this->processTags($template, ['repeater']);
foreach ($fields as $name => &$field) {
$outerTemplate = $tags[$name];
$innerTemplate = $field['default'];
unset($field['default']);
list($innerTags, $innerFields) = $this->processTags($innerTemplate);
list($openTag, $closeTag) = explode($innerTemplate, $outerTemplate);
$field['fields'] = $innerFields;
$tags[$name] = [
'tags' => $innerTags,
'template' => $outerTemplate,
'open' => $openTag,
'close' => $closeTag
];
// Remove the inner content of the repeater
// tag to prevent further parsing
$template = str_replace($outerTemplate, $openTag.$closeTag, $template);
}
return [$template, $tags, $fields];
}
/**
* Processes all registered tags against a template.
* @param string $template
* @param array $usingTags
* @return array
*/
protected function processTags($template, $usingTags = null)
{
if (!$usingTags) {
$usingTags = $this->registeredTags;
}
if ($this->tagPrefix) {
foreach ($usingTags as $tag) {
$usingTags[] = $this->tagPrefix . $tag;
}
}
$tags = [];
$fields = [];
$result = $this->processTagsRegex($template, $usingTags);
$tagStrings = $result[0];
$tagNames = $result[1];
$paramStrings = $result[2];
// These fields take options for selection
$optionables = [
'dropdown',
'radio',
'checkboxlist',
'balloon-selector',
];
// These fields take available colors for selection
$availableColors = [
'colorpicker',
];
foreach ($tagStrings as $key => $tagString) {
$tagName = $tagNames[$key];
$params = $this->processParams($paramStrings[$key], $tagName);
if (isset($params['name'])) {
$name = $params['name'];
unset($params['name']);
} else {
$name = md5($tagString);
}
if ($tagName == 'variable') {
$params['X_WINTER_IS_VARIABLE'] = true;
$tagName = array_get($params, 'type', 'text');
}
$params['type'] = $tagName;
if (in_array($tagName, $optionables) && isset($params['options'])) {
$params['options'] = $this->processOptionsToArray($params['options']);
}
if (in_array($tagName, $availableColors) && isset($params['availableColors'])) {
$params['availableColors'] = $this->processOptionsToArray($params['availableColors']);
}
// Convert trigger property to array
if (isset($params['trigger'])) {
$params['trigger'] = $this->processOptionsToArray($params['trigger']);
}
$tags[$name] = $tagString;
$fields[$name] = $params;
}
return [$tags, $fields];
}
/**
* Processes group 2 from the Tag regex and returns
* an array of captured parameters.
* @param string $value
* @param string $tagName
* @return array
*/
protected function processParams($value, $tagName)
{
$close = Parser::CHAR_CLOSE;
$closePos = strpos($value, $close);
$defaultValue = '';
if ($closePos === false) {
$paramString = $value;
}
elseif (substr($value, -1) == $close) {
$paramString = substr($value, 0, -1);
}
else {
$paramString = substr($value, 0, $closePos);
$defaultValue = trim(substr($value, $closePos + 1));
}
$result = $this->processParamsRegex($paramString);
$paramNames = $result[1];
$paramValues = $result[2];
// Convert all 'true' and 'false' string values to boolean values
foreach ($paramValues as $key => $value) {
if ($value === 'true' || $value === 'false') {
$paramValues[$key] = $value === 'true';
}
}
$params = array_combine($paramNames, $paramValues);
if ($tagName == 'checkbox') {
$params['_content'] = $defaultValue;
}
else {
$params['default'] = $defaultValue;
}
return $params;
}
/**
* Converts parameter string to an array.
*
* In: name="test" comment="This is a test"
* Out: ['name' => 'test', 'comment' => 'This is a test']
*
* @param string $string
* @return array
*/
protected function processParamsRegex($string)
{
/*
* Match key/value pairs
*
* (\w+)="((?:\\.|[^"\\]+)*|[^"]*)"
*/
$regex = '#';
$regex .= '(\w+)'; // Any word
$regex .= '="'; // Equal sign and open quote
$regex .= '('; // Capture
$regex .= '(?:\\\\.|[^"\\\\]+)*'; // Include escaped quotes \"
$regex .= '|[^"]'; // Or anything other than a quote
$regex .= '*)'; // Capture value
$regex .= '"';
$regex .= '#';
preg_match_all($regex, $string, $match);
return $match;
}
/**
* Performs a regex looking for a field type (key) and returns
* an array where:
*
* 0 - The full tag definition, eg: {text name="test"}Foobar{/text}
* 1 - The opening and closing tag name
* 2 - The tag parameters as a string, eg: name="test"} and;
* 2 - The default text inside the tag (optional), eg: Foobar
*
* @param string $string
* @param array $tags
* @return array
*/
protected function processTagsRegex($string, $tags)
{
/*
* Match opening and close tags
*
* {(text|textarea)\s([\S\s]+?){/(?:\1)}
*/
$open = preg_quote(Parser::CHAR_OPEN);
$close = preg_quote(Parser::CHAR_CLOSE);
$tags = implode('|', $tags);
$regex = '#';
$regex .= $open.'('.$tags.')\s'; // Group 1
$regex .= '([\S\s]+?)'; // Group 2 (Non greedy)
$regex .= $open.'/(?:\1)'.$close; // Group X (Not captured)
$regex .= '#';
preg_match_all($regex, $string, $match);
return $match;
}
/**
* Splits an option string to an array.
*
* one|two -> [one, two]
* one:One|two:Two -> [one => 'One', two => 'Two']
* \Path\To\Class::method -> \Path\To\Class::method(): array
*
* @param string $optionsString
* @throws ApplicationException if an invalid array is returned when using the callback method.
* @return array
*/
protected function processOptionsToArray($optionsString)
{
$result = [];
if (str_contains($optionsString, '::')) {
$options = explode('::', $optionsString);
if (count($options) === 2 && class_exists($options[0]) && method_exists($options[0], $options[1])) {
$result = $options[0]::{$options[1]}();
if (!is_array($result)) {
throw new ApplicationException(sprintf(
'Invalid dropdown option array returned by `%s::%s`',
$options[0],
$options[1]
));
}
return $result;
}
}
$options = explode('|', $optionsString);
foreach ($options as $index => $optionStr) {
$parts = explode(':', $optionStr, 2);
if (count($parts) > 1) {
$key = trim($parts[0]);
if (strlen($key)) {
if (!preg_match('/^[0-9a-z-_]+$/i', $key)) {
throw new ApplicationException(sprintf(
'Invalid drop-down option key: %s. Option keys can contain only digits, Latin letters and characters _ and -',
$key
));
}
$result[$key] = trim($parts[1]);
}
else {
$result[$index] = trim($optionStr);
}
}
else {
$result[$index] = trim($optionStr);
}
}
return $result;
}
}